0
0
Embedded Cprogramming~5 mins

PWM generation using timers in Embedded C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Software PWM generation
O(period)
Understanding Time Complexity

When generating PWM signals with a software loop, it's important to understand how the code execution time changes as period or duty cycle values change.

We want to know how the program's running time grows when controlling PWM with a software loop.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


// Simple software PWM generation
void generate_pwm(int duty_cycle, int period) {
    for (int i = 0; i < period; i++) {
        if (i < duty_cycle) {
            set_pin_high();
        } else {
            set_pin_low();
        }
        delay_one_unit();
    }
}
    

This code creates a PWM signal by turning a pin on or off for each unit of the period based on the duty cycle.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that runs once for each unit of the PWM period.
  • How many times: It runs exactly period times, controlling the signal timing.
How Execution Grows With Input

As the period increases, the loop runs more times, so the total work grows directly with the period size.

Input Size (period)Approx. Operations (loop iterations)
1010
100100
10001000

Pattern observation: The execution time grows in a straight line with the period size.

Final Time Complexity

Time Complexity: O(period)

This means the time to generate the PWM signal grows directly with the length of the period.

Common Mistake

[X] Wrong: "The time to generate PWM depends on the duty cycle only."

[OK] Correct: The loop runs for the entire period, not just the duty cycle, so the period size controls the total time.

Interview Connect

Understanding how timing loops affect execution time helps you explain embedded system behavior clearly and confidently.

Self-Check

"What if we replaced the for-loop with an interrupt-driven timer callback? How would the time complexity change?"