Delay and measure CPU cycles with DWT on STM32
Enable the DWT cycle counter on a supported Cortex-M and use unsigned counter differences for measurement and short delays.
Initialize and use CYCCNT
Cortex-M3 and Cortex-M4 implementations used by many STM32F1 and STM32F4 parts expose DWT CYCCNT. Enable tracing and inspect the implementation's counter support. Test that the counter advances on the target before calling a blocking delay. Other cores may lack the counter or require DWT unlock, so use a hardware timer on those devices.
The unsigned difference works across one 32-bit wrap. Choose a short duration and avoid resetting the counter while another caller is measuring it. Convert a time to cycles with the actual CPU clock, using a wide intermediate to avoid arithmetic overflow. Interrupt service delays extend the wall-clock time spent in a busy wait.
bool start_cycle_counter(void) {
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
if (DWT->CTRL & DWT_CTRL_NOCYCCNT_Msk) return false;
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
uint32_t start = DWT->CYCCNT;
__NOP();
__NOP();
return DWT->CYCCNT != start;
}
void delay_cycles(uint32_t cycles) {
uint32_t start = DWT->CYCCNT;
while ((uint32_t)(DWT->CYCCNT - start) < cycles) {}
}Measure a routine
Read CYCCNT just before and after the routine. Keep the routine's output observable so the optimizer cannot remove the work. Report the optimization level and clock. Compare repeated measurements and time an empty measurement to estimate overhead.
