0
0
FreeRTOSprogramming~5 mins

vTaskGetRunTimeStats() for CPU usage in FreeRTOS

Choose your learning style9 modes available
Introduction

This function helps you see how much CPU time each task uses. It shows which tasks are working hard and which are idle.

You want to check which tasks use the most CPU in your FreeRTOS system.
You need to find tasks that slow down your program by using too much CPU.
You want to optimize your system by balancing CPU usage among tasks.
You are debugging and want to see if any task is stuck or hogging the CPU.
Syntax
FreeRTOS
void vTaskGetRunTimeStats( char *pcWriteBuffer );

You must provide a buffer (string) where the stats will be stored.

The buffer should be large enough to hold all the stats text.

Examples
This example creates a buffer, gets the CPU usage stats, and prints them.
FreeRTOS
char buffer[512];
vTaskGetRunTimeStats(buffer);
printf("%s", buffer);
Here, the stats are stored in a smaller buffer for later use.
FreeRTOS
char stats[256];
vTaskGetRunTimeStats(stats);
// Use stats string to display on screen or log
Sample Program

This program creates two simple tasks and a stats task. The stats task prints CPU usage stats every second. The FreeRTOS scheduler runs indefinitely.

FreeRTOS
#include "FreeRTOS.h"
#include "task.h"
#include <stdio.h>

void vTask1(void *pvParameters) {
    for (;;) {
        // Task code here
        vTaskDelay(pdMS_TO_TICKS(100));
    }
}

void vTask2(void *pvParameters) {
    for (;;) {
        // Task code here
        vTaskDelay(pdMS_TO_TICKS(200));
    }
}

void vStatsTask(void *pvParameters) {
    char statsBuffer[512];
    for (;;) {
        vTaskGetRunTimeStats(statsBuffer);
        printf("CPU Usage Stats:\n%s", statsBuffer);
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

int main(void) {
    xTaskCreate(vTask1, "Task1", 1000, NULL, 1, NULL);
    xTaskCreate(vTask2, "Task2", 1000, NULL, 1, NULL);
    xTaskCreate(vStatsTask, "Stats", 1000, NULL, 1, NULL);

    vTaskStartScheduler();

    for(;;) {}

    return 0;
}
OutputSuccess
Important Notes

You must enable configGENERATE_RUN_TIME_STATS in FreeRTOSConfig.h for this function to work.

You need a timer or counter to measure run time; FreeRTOS uses this to calculate CPU usage.

The output format is a table showing each task's name, total run time, and percentage of CPU time.

Summary

vTaskGetRunTimeStats() shows CPU time used by each FreeRTOS task.

Use it to find which tasks use most CPU and optimize your system.

Remember to enable run time stats and provide a big enough buffer for results.