0
0
Embedded Cprogramming~5 mins

Duty cycle control for motor/LED in Embedded C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Duty cycle control for motor/LED
O(1)
Understanding Time Complexity

We want to understand how the time it takes to control the duty cycle changes as we adjust the input size.

Specifically, how does the program's work grow when changing the duty cycle steps?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


void setDutyCycle(int dutyCyclePercent) {
    for (int i = 0; i < 100; i++) {
        if (i < dutyCyclePercent) {
            turnOnOutput();
        } else {
            turnOffOutput();
        }
        delayMicroseconds(10);
    }
}
    

This code sets the duty cycle by turning the output on or off in a loop of 100 steps, simulating PWM control.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop running 100 times to set output on/off.
  • How many times: Always 100 times, regardless of dutyCyclePercent.
How Execution Grows With Input

The loop always runs 100 times, so the work stays the same no matter the duty cycle value.

Input Size (dutyCyclePercent)Approx. Operations
10100 loop steps
50100 loop steps
90100 loop steps

Pattern observation: The number of operations does not change with input size; it stays constant.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the code stays the same no matter what duty cycle value you use.

Common Mistake

[X] Wrong: "If I increase the duty cycle percent, the program will take longer to run because it turns on more."

[OK] Correct: The loop always runs 100 times no matter what, so the total steps stay the same. Turning on or off inside the loop doesn't change how many times the loop runs.

Interview Connect

Understanding how loops and input sizes affect time helps you explain how embedded systems keep timing precise and predictable.

Self-Check

"What if the loop ran up to the dutyCyclePercent value instead of always 100? How would the time complexity change?"