PWM generation using timers in Embedded C - Time & Space 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.
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 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
periodtimes, controlling the signal timing.
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) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The execution time grows in a straight line with the period size.
Time Complexity: O(period)
This means the time to generate the PWM signal grows directly with the length of the period.
[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.
Understanding how timing loops affect execution time helps you explain embedded system behavior clearly and confidently.
"What if we replaced the for-loop with an interrupt-driven timer callback? How would the time complexity change?"