Why priority design matters in FreeRTOS - Performance Analysis
When tasks have different priorities in FreeRTOS, how fast the system responds depends on how priorities are designed.
We want to see how task priority affects the time it takes to switch and run tasks.
Analyze the time complexity of this task switching code snippet.
// Simplified FreeRTOS task switch based on priority
void vTaskSwitchContext(void) {
TaskHandle_t pxNextTask = NULL;
for (int priority = configMAX_PRIORITIES - 1; priority >= 0; priority--) {
if (listGET_HEAD_ENTRY(&pxReadyTasksLists[priority]) != NULL) {
pxNextTask = listGET_OWNER_OF_HEAD_ENTRY(&pxReadyTasksLists[priority]);
break;
}
}
if (pxNextTask != pxCurrentTask) {
pxCurrentTask = pxNextTask;
// context switch happens here
}
}
This code finds the highest priority ready task to run next by checking task lists from highest to lowest priority.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop through priority levels to find a ready task.
- How many times: Up to the number of priority levels (configMAX_PRIORITIES).
As the number of priority levels grows, the time to find the next task grows linearly.
| Input Size (priority levels) | Approx. Operations (checks) |
|---|---|
| 5 | Up to 5 checks |
| 10 | Up to 10 checks |
| 32 | Up to 32 checks |
Pattern observation: More priority levels mean more checks, so time grows in a straight line with priority count.
Time Complexity: O(n)
This means the time to select the next task grows directly with the number of priority levels.
[X] Wrong: "Adding more priority levels won't affect task switching time much."
[OK] Correct: Each added priority level means the scheduler may check more lists, increasing the time to find the next task.
Understanding how priority design affects task switching time helps you write efficient real-time systems that respond quickly and predictably.
"What if the scheduler used a bitmap to track ready priorities instead of looping? How would the time complexity change?"