Calculating CPU usage for the task

I know that vTaskGetRunTimeStats is calculating the CPU usage by dividing the total execution time of the task by the total execution for the system. but is it the correct way to show the CPU usage or we should calculate the execution time of the task within specific window (1 second for example) periodically, so every time the CPU usage is displayed, it will show the correct indication for the current task CPU usage

It depends what it is you are trying to measure. Unless you are using a low power mode the CPU will be running all the time. If you want to know the spare CPU capacity then measure the amount of time the idle task is running (assuming there are no other tasks that are running at the idle priority). The longer you gather stats for the more accurate the result will be.

It sounds that I wasn’t clear in my question, I meant the task’s CPU usage not the all over CPU usage.

Hi Mohammed,

this should be fairly easy to implement yourself using the TCB’s ulRunTimeCounter member (unless it’s already present which I couldn’t check for the most recent version of FreeRTOS).