Watchdog task pattern in FreeRTOS - Time & Space Complexity
We want to understand how the time cost changes when running a watchdog task in FreeRTOS.
Specifically, how the task checks other tasks and how this scales as more tasks are added.
Analyze the time complexity of the following code snippet.
void WatchdogTask(void *pvParameters) {
for (;;) {
for (int i = 0; i < numTasks; i++) {
if (!IsTaskResponsive(i)) {
HandleUnresponsiveTask(i);
}
}
vTaskDelay(WATCHDOG_DELAY);
}
}
This code runs forever, checking each task once per cycle to see if it is responsive.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The inner for-loop that checks each task's responsiveness.
- How many times: It runs once every watchdog cycle, iterating over all tasks (numTasks times).
As the number of tasks increases, the watchdog checks more tasks each cycle.
| Input Size (numTasks) | Approx. Operations per Cycle |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of checks grows directly with the number of tasks.
Time Complexity: O(n)
This means the time to complete one watchdog cycle grows linearly as the number of tasks increases.
[X] Wrong: "The watchdog task runs in constant time no matter how many tasks there are."
[OK] Correct: Because the watchdog checks each task one by one, more tasks mean more checks, so time grows with the number of tasks.
Understanding how a watchdog task scales helps you design reliable systems and shows you can reason about task monitoring in real-time software.
"What if the watchdog only checked a fixed number of tasks each cycle instead of all tasks? How would the time complexity change?"