How do you measure task execution time and CPU load in an RTOS?
Short answer: Use the RTOS's run-time statistics (FreeRTOS configGENERATE_RUN_TIME_STATS with a fast timer, then vTaskGetRunTimeStats()), measure idle time to compute CPU load (load = 1 − idle time / total time), toggle GPIOs at task entry/exit and watch them on a logic analyser, or use trace tools (Percepio Tracealyzer, SEGGER SystemView) that record every context switch and interrupt with timestamps.
FreeRTOS run-time stats
/* FreeRTOSConfig.h */
#define configGENERATE_RUN_TIME_STATS 1
#define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() dwt_init() /* e.g. DWT cycle counter */
#define portGET_RUN_TIME_COUNTER_VALUE() (DWT->CYCCNT)
/* somewhere in a debug command */
char buf[512];
vTaskGetRunTimeStats(buf); /* "Task AbsTime %Time" per task, including IDLE */
The counter should run 10–100× faster than the tick for useful resolution.
Measuring a single function's WCET
uint32_t t0 = DWT->CYCCNT;
filter_update();
uint32_t cycles = DWT->CYCCNT - t0;
if (cycles > max_cycles) max_cycles = cycles; /* keep the worst seen */
Run it under worst-case conditions (all interrupts active, caches cold) and record the maximum, not the average.
GPIO method: set a pin high at task start, low at the end; an oscilloscope or logic analyser shows execution time, period and jitter for several tasks at once, with no software overhead to speak of. Great for checking real-time behaviour and interrupt latency.
Trace tools show the whole timeline: which task ran when, blocking reasons, response times and missed deadlines. They are the fastest way to understand priority problems.
CPU load target: keep peak load below about 70–80% to leave headroom for worst-case bursts and future features, and alarm in diagnostics if idle time falls below a threshold.