Calculating the number of task switching per second

Hello,
I’m trying to calculate the number of tasks per seconds and i’m using STM32H7 with 1000HZ tick rate.
I tried to use traceTASK_SWITCHED_IN hook function beside traceTASK_INCREMENT_TICK hook function.

void PROBE_vTraceTaskSwitchIn()// is corresponding to traceTASK_SWITCHED_IN
{
u16SwitchCounter++;
}
void PROBE_vTraceTickIncrement(TickType_t ticks)// is corresponding to traceTASK_SWITCHED_IN
{
if((ticks % configTICK_RATE_HZ) == 0U)
{
u16SwitchCounterRate = u16SwitchCounter;
u16SwitchCounter = 0U;
}
}
the problem that the task context switching rate output is 2000 which it should be 1000 as a maximum.
so where is the problem.

Thanks,
Mohammed

There is no maximum switch rate, as any time a task blocks, like on a queue or semaphore, or a delay call, you get a task switch. The 1000 Hz tic rate forms a sort of floor for the switch rate as it will check to see if the current task needs to be swapped for another ready task at the same priority level.

Does the OS do the context switching every tick, which is 1000 time per second?
also, when the traceTASK_SWITCHED_IN is invoked? is it when the task become ready or when the task start to run?

A context switch occurs any time a task entering the ready state has a priority above the currently running task - or a tick interrupt occurs when there is more than one task at the same priority (assuming configUSE_TIME_SLICING is not set to zero). That is about it.

I recommend reading the book, which explains when a context switch occurs.

The OS will context switch every time a new task gets a chance to run. This opportunity happens at least every tick, since that is when the OS checks to see if there are multiple tasks at the priority level of the currently running task that are ready.

It also has to happen any time the current task blocks to wait for a queue, semaphore, does a delay, etc.

It can also happen if the current task or an interrupt does something to wake up a task with a higher priority than the current task, like put something on a queue or signals a semaphore.

The OS does NOT wait for the next tick to see who to run next, as soon as another task of higher priority is woken by the thing it is blocking on becoming ready, the system will switch. Also, if the current task becomes not ready the system needs to switch.

traceTASK_SWITCHED_IN is run as the task gets switched to.

1 Like