Feeding (kicking) the watchdog in Embedded C - Time & Space Complexity
We want to understand how the time to feed the watchdog changes as the program runs.
How often does the feeding action happen as the system runs?
Analyze the time complexity of the following code snippet.
void feed_watchdog(void) {
WDT->CLEAR = WDT_CLEAR_KEY;
}
int main(void) {
while(1) {
// ... other tasks ...
feed_watchdog();
}
return 0;
}
This code repeatedly feeds the watchdog inside an infinite loop to prevent system reset.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The infinite loop calling
feed_watchdog(). - How many times: The feeding happens continuously, as many times as the loop runs.
Since the loop runs forever, the feeding operation happens repeatedly without end.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 feedings |
| 100 | 100 feedings |
| 1000 | 1000 feedings |
Pattern observation: The number of feedings grows directly with the number of loop iterations.
Time Complexity: O(n)
This means the feeding operation happens once per loop iteration, growing linearly with the number of iterations.
[X] Wrong: "Feeding the watchdog is a one-time setup and does not repeat."
[OK] Correct: The watchdog must be fed regularly inside the loop to prevent reset, so it repeats continuously.
Understanding how often a watchdog is fed helps show you can reason about repeated operations in embedded systems, a useful skill for real-world programming.
"What if the feeding was done only once outside the loop? How would the time complexity change?"