Calculating total CPU load

I’m trying to calculate the CPU load using the idle task execution time and traceTASK_INCREMENT_TICK. the system is using 1000 tick/second such that configTICK_RATE_HZ is equal 1000.

void PROBE_vTraceTickIncrement(TickType_t ticks) //corresponding to traceTASK_INCREMENT_TICK
{
static INT32U u32LastIdleRunTime = 0;
          INT32U u32TempTime;
    if((ticks % configTICK_RATE_HZ) == 0U)
    {
	u32TempTime = ulTaskGetIdleRunTimeCounter();
	u16IdleTaskUtilizationInTicks = u32TempTime - u32LastIdleRunTime;
	u32LastIdleRunTime = u32TempTime;
    }
}

the issue that some times the u16IdleTaskUtilizationInTicks is greater than 1000 while it should be less or equal 1000.
I know that the first run for the function incorrect value but later it shall work properly.

It is not clear how this is working. I would recommend using the traceTASK_SWITCHED_IN macro in place of traceTASK_INCREMENT_TICK and the idle task may run many time or never between tick increments. You can use traceTASK_SWITCHED_IN to see if it is the idle task being switched in to start a timer, and if any other task is being switched in to stop a timer.

There’s a special task called the idle task that runs when no other task can be run. The % usage is just the percentage of the time we’re not running the idle task. The OS will keep a running total of the time spent running the idle task:

  • when we switch to the idle task, set t = current time
  • when we switch away from the idle task, add (current time - t) to the running total

If we take two samples of the running total n seconds apart, we can calculate the percentage of those n seconds spent running the idle task as (second sample - first sample)/n

Note that this is something the OS does, not the CPU. The concept of a task doesn’t exist at the CPU level! (In practice, the idle task will put the processor to sleep with a HLT instruction, so the CPU does know when it isn’t being used).