Watchdog timer operation in Embedded C - Time & Space Complexity
We want to understand how the time taken by a watchdog timer operation changes as the program runs.
Specifically, how often the watchdog reset happens affects the program's timing.
Analyze the time complexity of the following code snippet.
void watchdog_reset() {
WDT->CLEAR = 0xA5; // Reset watchdog timer
}
void main_loop(int n) {
for (int i = 0; i < n; i++) {
// Some processing
watchdog_reset();
}
}
This code resets the watchdog timer inside a loop that runs n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop running n times calling
watchdog_reset(). - How many times: Exactly n times, once per loop iteration.
As n grows, the number of times the watchdog reset happens grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 watchdog resets |
| 100 | 100 watchdog resets |
| 1000 | 1000 watchdog resets |
Pattern observation: The operations increase directly with n, doubling n doubles the work.
Time Complexity: O(n)
This means the time taken grows in direct proportion to the number of loop iterations.
[X] Wrong: "The watchdog reset happens only once, so time is constant."
[OK] Correct: The reset is inside the loop, so it happens every time the loop runs, making time grow with n.
Understanding how loops affect timing is key in embedded systems, especially for safety features like watchdog timers.
"What if the watchdog reset was moved outside the loop? How would the time complexity change?"