vTaskList() for task status dump in FreeRTOS - Time & Space Complexity
We want to understand how the time to run vTaskList() changes as the number of tasks grows.
This helps us know how long it takes to get a snapshot of all task statuses.
Analyze the time complexity of the following code snippet.
void vTaskList( char *pcWriteBuffer )
{
TaskStatus_t *pxTaskStatusArray;
UBaseType_t uxArraySize, x;
uxArraySize = uxTaskGetNumberOfTasks();
pxTaskStatusArray = pvPortMalloc( uxArraySize * sizeof( TaskStatus_t ) );
uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, NULL );
for( x = 0; x < uxArraySize; x++ )
{
/* Write task info to pcWriteBuffer */
}
vPortFree( pxTaskStatusArray );
}
This code collects the current state of all tasks and writes their status into a buffer.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over all tasks to write their status.
- How many times: Once for each task, so as many times as there are tasks.
As the number of tasks increases, the time to list them grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 operations |
| 100 | About 100 operations |
| 1000 | About 1000 operations |
Pattern observation: Doubling the number of tasks roughly doubles the work done.
Time Complexity: O(n)
This means the time to get the task list grows directly with the number of tasks.
[X] Wrong: "The time to get the task list stays the same no matter how many tasks there are."
[OK] Correct: Because the function must check each task once, more tasks mean more work and more time.
Knowing how system functions scale with input size helps you write efficient embedded code and explain your reasoning clearly.
"What if the function also collected detailed runtime stats for each task? How would the time complexity change?"