Simvik

Driver: measure worst-case time with the cycle counter

Enable the Cortex-M cycle counter and time a function across many runs, wraparound included. An easy embedded C problem (Timing, interrupts and concurrency),…

easy · Timing, interrupts and concurrency · driver · registers · dwt · timing

The Cortex-M DWT unit has a free-running cycle counter, CYCCNT, that counts only while CYCCNTENA is set in CTRL. In the simulation, a cycle is one statement.

Write measure_worst(fn, runs): make sure the counter is running, call fn runs times, timing each call on its own, and return the longest time in cycles. The counter may be anywhere when you start, close to wrapping included.

Starter code

uint32_t measure_worst(void (*fn)(void), int runs) {
  return 0;
}

Example tests

The slow path sets the worst case

uint32_t q = measure_worst(quick, 1), s = measure_worst(slow, 1);
uint32_t w = measure_worst(work, 8);
printf("quick < slow: %d\n", q < s);
printf("worst of work is the slow path: %d\n", w > (q + s) / 2 && w < s + s / 4);

Expected output:

quick < slow: 1
worst of work is the slow path: 1

Learn it first

More Timing, interrupts and concurrency problems