26. April 2021 · Categories: Software

freeRTOS has the ability to collect run time statistics when you activate the configuration configGENERATE_RUN_TIME_STATS. You still need to implement the timer yourself, though. On the Cortex-M processors, a pretty generic way is to use the system timer, so I adapted it to provide timing information with a 1µs resolution. Because freeRTOS uses 32bit numbers to store the counter, it will overflow after 70 minutes. For most performance checks that should be ample, but you can always change runTimeCountsPerSecond below to match your needs.

The code avoids costly divisions by first calculating the inverse, and scaling it with a shift to achieve a good compromise between speed and accuracy. This optimization is because the counter will be retrieved with every context switch, and so slightly distort the measurements.

Erich Styger shows a few alternatives. There I also learned that the tick counter must be atomic (portTICK_TYPE_IS_ATOMIC), which is always the case on Cortex-M, but could trip you on other CPUs.