Try Embedded

Nucleo-F401RE: count CPU cycles with the DWT

Time pieces of C to the clock cycle with the Cortex-M4's DWT cycle counter, and see what the compiler made of them: division against shifts, float against…

Firmware · Advanced

In a real product: Motor control loop timing (Robotics): Engineers measure the cycles each control step takes, to prove it fits in its time slot.

"Is this fast enough?" is a question you answer by measuring, not guessing. Every Cortex-M3 and up has a DWT (Data Watchpoint and Trace) unit, and in it a 32-bit counter that adds one on every CPU clock cycle. Reading it before and after a piece of code gives its cost in cycles. At 16 MHz one cycle is 62.5 ns.

This program times five pairs of code that do the same job in different ways, and prints the cycles for each.

What you'll learn

  • Starting the cycle counter: CoreDebug->DEMCR TRCENA, then DWT->CYCCNT and DWT->CTRL CYCCNTENA
  • What instructions a line of C turns into, and what they cost: UDIV against LSR, the FPU's VMUL.F32 against a library call for double, LDR/STR on each volatile access
  • Why a volatile loop counter makes a loop slower, and when you still need it
  • Subtracting the cost of the measurement itself

How it works

CoreDebug->DEMCR |= TRCENA powers the trace units, and DWT->CTRL |= CYCCNTENA starts the counter. cycles(f) reads CYCCNT, calls the function, and reads it again. Running an empty function first gives the overhead of the call and the two reads, which is subtracted from every result.

The pairs, and what to look for in the disassembly:

  • Divide or shift: x / 8 on an unsigned value is a shift (LSR, 1 cycle). x / d with d only known at run time needs UDIV, 2 to 12 cycles on a Cortex-M4.
  • float or double: the F401's FPU does single precision only. float multiplies are one VMUL.F32, while double calls __aeabi_dmul in software, dozens of cycles each.
  • volatile or not: a volatile variable is loaded and stored on every use. A plain one stays in a register, and here the compiler goes further: it adds up 0 to 63 itself and only stores the answer, 2016.
  • Table or calculation: a 256-entry lookup is one load. Counting bits one by one is a loop.
  • memcpy or a byte loop: here they are close. The build's C library (newlib-nano) is made small, not fast, and its memcpy copies a byte at a time too. A library built for speed copies whole words, about four times faster.

The numbers come from the simulator's model of the core's instruction timings, so the ratios are what matter. On a real board, flash wait states and the cache change them a little, which is the next reason to measure on the target.

Try this

  • Make divisor a plain static uint32_t that nothing writes: the compiler sees it is always 8, and the division costs the same as the shift.
  • Time x / 3.0f against x * (1.0f / 3.0f). Why can't the compiler make that change for you?
  • Time printf("%d", 12345): you'll see why printing in an interrupt is a bad idea.

main.c

// Bare-metal C on the Nucleo-F401RE: no Arduino core and no HAL. CMSIS names every register.
// Time pairs of C with the DWT cycle counter (16 MHz HSI: one cycle is 62.5 ns).
#include <stdio.h>
#include <string.h>
#include "stm32f4xx.h"

int __io_putchar(int ch) {
  while (!(USART2->SR & USART_SR_TXE)) {}
  USART2->DR = ch;
  return ch;
}

static uint32_t overhead;

// The cycles a call to f takes, without the cost of measuring.
static uint32_t cycles(void (*f)(void)) {
  uint32_t start = DWT->CYCCNT;
  f();
  return DWT->CYCCNT - start - overhead;
}

static volatile uint32_t sink;          // results go here, so the compiler can't drop the work
static uint32_t data[64];
static volatile uint32_t divisor = 8;   // volatile: the compiler can't know it stays 8
static uint8_t src[256], dst[256], bits[256];
static volatile float fin = 1.5f;
static volatile double din = 1.5;

static void nothing(void) {}
static void div_shift(void) { uint32_t s = 0; for (int i = 0; i < 64; i++) s += data[i] / 8; sink = s; }
static void div_udiv(void)  { uint32_t s = 0, d = divisor; for (int i = 0; i < 64; i++) s += data[i] / d; sink = s; }
static void mul_float(void) { float x = fin; for (int i = 0; i < 16; i++) x = x * 1.0001f; sink = (uint32_t)x; }
static void mul_double(void){ double x = din; for (int i = 0; i < 16; i++) x = x * 1.0001; sink = (uint32_t)x; }
static void loop_plain(void) { uint32_t s = 0; for (uint32_t i = 0; i < 64; i++) s += i; sink = s; }
static void loop_volatile(void) { volatile uint32_t s = 0; for (volatile uint32_t i = 0; i < 64; i++) s += i; sink = s; }
static void ones_table(void) { uint32_t n = 0; for (int i = 0; i < 64; i++) n += bits[data[i] & 0xFF]; sink = n; }
static void ones_loop(void)  {
  uint32_t n = 0;
  for (int i = 0; i < 64; i++) for (uint32_t v = data[i] & 0xFF; v; v >>= 1) n += v & 1;
  sink = n;
}
static void copy_memcpy(void) { memcpy(dst, src, sizeof dst); sink = dst[255]; }
static void copy_bytes(void)  {                // volatile, so it stays a byte loop (else GCC calls memcpy)
  volatile uint8_t *d = dst;
  for (int i = 0; i < 256; i++) d[i] = src[i];
  sink = dst[255];
}

static void compare(const char *what, const char *a, void (*fa)(void), const char *b, void (*fb)(void)) {
  uint32_t ca = cycles(fa), cb = cycles(fb);
  printf("%-18s %-12s %5lu   %-12s %5lu\r\n", what, a, (unsigned long)ca, b, (unsigned long)cb);
}

int main(void) {
  RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
  RCC->APB1ENR |= RCC_APB1ENR_USART2EN;
  GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER2) | GPIO_MODER_MODER2_1;
  GPIOA->AFR[0] = (GPIOA->AFR[0] & ~(0xFu << 8)) | (7u << 8);
  USART2->BRR = SystemCoreClock / 115200;
  USART2->CR1 = USART_CR1_TE | USART_CR1_UE;

  CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;   // power the trace units
  DWT->CYCCNT = 0;
  DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;               // count every cycle

  for (int i = 0; i < 64; i++) data[i] = i * 2654435761u;
  for (int i = 0; i < 256; i++) { src[i] = i; bits[i] = __builtin_popcount(i); }
  overhead = 0;
  overhead = cycles(nothing);
  printf("Measuring costs %lu cycles, taken off below\r\n\r\n", (unsigned long)overhead);

  compare("64 divisions", "x / 8", div_shift, "x / divisor", div_udiv);
  compare("16 multiplies", "float", mul_float, "double", mul_double);
  compare("64 additions", "plain", loop_plain, "volatile", loop_volatile);
  compare("64 bit counts", "table", ones_table, "loop", ones_loop);
  compare("copy 256 bytes", "memcpy", copy_memcpy, "byte loop", copy_bytes);
  for (;;) {}
}

Lessons behind it