Idle mode behavior in Embedded C - Time & Space Complexity
When a program enters idle mode, it waits without doing much work. We want to understand how this waiting affects the program's running time.
How does the program's time change when it spends time idling?
Analyze the time complexity of the following code snippet.
void idle_mode(int wait_cycles) {
while(wait_cycles > 0) {
// CPU does nothing but waits
wait_cycles--;
}
}
This code makes the CPU wait by counting down from a number until zero, simulating idle time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that decreases
wait_cyclesby one each time. - How many times: Exactly as many times as the initial value of
wait_cycles.
As the number of wait cycles increases, the program spends more time looping.
| Input Size (wait_cycles) | Approx. Operations |
|---|---|
| 10 | 10 loop steps |
| 100 | 100 loop steps |
| 1000 | 1000 loop steps |
Pattern observation: The time grows directly with the number of wait cycles; doubling wait cycles doubles the time.
Time Complexity: O(n)
This means the time the program spends idling grows in a straight line with the number of wait cycles.
[X] Wrong: "Idle mode takes constant time no matter how long we wait."
[OK] Correct: Even though the CPU is not doing useful work, the loop still runs once per wait cycle, so time grows with the wait length.
Understanding idle mode time helps you reason about how waiting affects program speed, a useful skill when working with embedded systems or low-power devices.
"What if we replaced the while loop with a hardware timer interrupt that pauses the CPU without looping? How would the time complexity change?"