vTaskGetRunTimeStats() for CPU usage in FreeRTOS - Time & Space Complexity
We want to understand how the time to gather CPU usage stats grows as the number of tasks increases.
How does the function's work change when there are more tasks to check?
Analyze the time complexity of the following code snippet.
void vTaskGetRunTimeStats( 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++ ) {
sprintf( pcWriteBuffer, "%s %lu\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter );
pcWriteBuffer += strlen( pcWriteBuffer );
}
vPortFree( pxTaskStatusArray );
}
This code collects CPU usage stats for all tasks and writes them into a buffer.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through each task to write its stats.
- How many times: Once for each task, so as many times as there are tasks.
As the number of tasks grows, the function spends more time writing stats for each one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 tasks | About 10 writes to the buffer |
| 100 tasks | About 100 writes to the buffer |
| 1000 tasks | About 1000 writes to the buffer |
Pattern observation: The work grows directly with the number of tasks.
Time Complexity: O(n)
This means the time to get CPU stats grows in a straight line as tasks increase.
[X] Wrong: "The function runs in constant time no matter how many tasks there are."
[OK] Correct: The function must look at each task to get its stats, so more tasks mean more work.
Understanding how functions scale with input size helps you write efficient code and explain your reasoning clearly.
"What if the function also sorted the tasks by CPU usage before writing? How would the time complexity change?"