Sleep modes overview in Embedded C - Time & Space Complexity
When using sleep modes in embedded C, it's important to understand how the program's execution time changes.
We want to see how the time spent running code grows when sleep modes are involved.
Analyze the time complexity of the following code snippet.
void main_loop() {
while(1) {
do_task();
enter_sleep_mode();
}
}
void do_task() {
// Some fixed time work
}
void enter_sleep_mode() {
// MCU sleeps until interrupt
}
This code runs a task repeatedly, then puts the microcontroller to sleep until an interrupt wakes it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The infinite while loop repeating do_task and sleep.
- How many times: Runs indefinitely, repeating the task and sleep cycle.
Since the loop runs forever, the total execution time grows linearly with the number of cycles.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 cycles | 10 task executions + 10 sleeps |
| 100 cycles | 100 task executions + 100 sleeps |
| 1000 cycles | 1000 task executions + 1000 sleeps |
Pattern observation: The number of operations grows directly with the number of cycles.
Time Complexity: O(n)
This means the total time grows in a straight line as the number of task and sleep cycles increases.
[X] Wrong: "Sleep mode makes the program run faster overall."
[OK] Correct: Sleep mode pauses the CPU, so it saves power but does not reduce the number of task cycles or their time.
Understanding how sleep modes affect program flow and timing helps you explain embedded system behavior clearly and confidently.
"What if the do_task function took time proportional to input size? How would the time complexity change?"