Duty cycle control for motor/LED in Embedded C - Time & Space 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?
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 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.
The loop always runs 100 times, so the work stays the same no matter the duty cycle value.
| Input Size (dutyCyclePercent) | Approx. Operations |
|---|---|
| 10 | 100 loop steps |
| 50 | 100 loop steps |
| 90 | 100 loop steps |
Pattern observation: The number of operations does not change with input size; it stays constant.
Time Complexity: O(1)
This means the time to run the code stays the same no matter what duty cycle value you use.
[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.
Understanding how loops and input sizes affect time helps you explain how embedded systems keep timing precise and predictable.
"What if the loop ran up to the dutyCyclePercent value instead of always 100? How would the time complexity change?"