CPU Usage

Class to provide a CPU usage indication based on task callback availability. To produce useful results it requires a couple of seconds at startup to calibrate.

Use like this:

#include <Services/Profiling/CpuUsage.h>

// instantiate a single instance of :cpp:class:`Profiling::CpuUsage`
Profiling::CpuUsage cpuUsage;

// Will be called when CpuUsage calibration has completed
void onReady()
   // Continue with application initialisation

void init()
   // Begin clock calibration

See RingTonePlayer for a more detailed example.

CPU usage is calculated over an update period which begins with a call to Profiling::CpuUsage::reset(). The actual update period must be managed elsewhere, using a callback timer, web request or other mechanism. It doesn’t need to be exact as the actual elapsed time in CPU cycles is used for the calculation.

After the update period has elapsed, call Profiling::CpuUsage::getUtilisation() to obtain a CPU usage figure.

This figure is obtained using the number of task callbacks made within the update period.

loop cycles

Set up repeating task callback and measure invocations between successive calls

total cycles

The total number of CPU cycles between calls to Profiling::CpuUsage::update().


total - loop


used / total

class Profiling::CpuUsage

Class to provide a CPU usage indication based on task callback availability.

Public Functions

inline void begin(InterruptCallback ready)

Calibrate the baseline figure for minimum CPU usage.


Typically call this in init()


ready – Function to call when calibration is complete

inline void reset()

Reset counters to start a new update period.

inline unsigned getLoopIterations()

Get the number of task callbacks made so far.

inline uint32_t getElapsedCycles()

Get the total number of CPU cycles since the last call to reset()

inline uint32_t getMinLoopCycles()

Get the figure used as the baseline cycle count.

inline unsigned getUtilisation()

Get the CPU utilisation figure in 1/100ths of a percent.