0
0
FreeRTOSprogramming~5 mins

vTaskGetRunTimeStats() for CPU usage in FreeRTOS - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: vTaskGetRunTimeStats() for CPU usage
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of tasks grows, the function spends more time writing stats for each one.

Input Size (n)Approx. Operations
10 tasksAbout 10 writes to the buffer
100 tasksAbout 100 writes to the buffer
1000 tasksAbout 1000 writes to the buffer

Pattern observation: The work grows directly with the number of tasks.

Final Time Complexity

Time Complexity: O(n)

This means the time to get CPU stats grows in a straight line as tasks increase.

Common Mistake

[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.

Interview Connect

Understanding how functions scale with input size helps you write efficient code and explain your reasoning clearly.

Self-Check

"What if the function also sorted the tasks by CPU usage before writing? How would the time complexity change?"