Priority-based scheduling in FreeRTOS - Time & Space Complexity
When using priority-based scheduling in FreeRTOS, tasks are chosen based on their priority levels.
We want to understand how the time to pick the next task changes as the number of tasks grows.
Analyze the time complexity of the following code snippet.
// Simplified task selection in FreeRTOS
TaskHandle_t xTaskToRun = NULL;
for (int priority = configMAX_PRIORITIES - 1; priority >= 0; priority--) {
if (listLIST_IS_EMPTY(&pxReadyTasksLists[priority]) == pdFALSE) {
xTaskToRun = listGET_OWNER_OF_HEAD_ENTRY(&pxReadyTasksLists[priority]);
break;
}
}
// xTaskToRun now points to the highest priority ready task
This code checks task lists from highest to lowest priority to find the next task to run.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over priority levels from highest to lowest.
- How many times: Up to
configMAX_PRIORITIEStimes, which is a fixed number.
The loop runs once for each priority level until it finds a ready task.
| Input Size (Number of Priorities) | Approx. Operations |
|---|---|
| 5 | Up to 5 checks |
| 10 | Up to 10 checks |
| 32 | Up to 32 checks |
Pattern observation: The number of checks grows linearly with the number of priority levels, but this number is usually fixed and small.
Time Complexity: O(1)
This means the time to select the next task does not grow with the number of tasks, only with the fixed number of priority levels.
[X] Wrong: "The scheduler checks every task every time, so time grows with total tasks."
[OK] Correct: The scheduler only checks priority lists, not every task individually, so time depends on priority count, not total tasks.
Understanding how priority-based scheduling scales helps you explain real-time system behavior clearly and confidently.
"What if the number of priority levels was not fixed but grew with the number of tasks? How would the time complexity change?"