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: 1Learn it first
- Interrupts, timing and concurrency · How interrupts work on a Cortex-M, priorities, latency, races, rollover-safe time, non-blocking code and debouncing.
More Timing, interrupts and concurrency problems
- Elapsed time across rollover · Compute how many ticks have passed, even when the counter has wrapped.
- Rollover-safe timeout · Decide whether a timeout has expired without being fooled by wrap-around.
- Non-blocking blink · Derive an LED state from the current time instead of calling delay.
- Milliseconds to ticks · Convert a delay in milliseconds to RTOS ticks, rounding up.
- Debounce a button · Accept a new button state only after it has been stable for several samples.
- Periodic software timer · Fire once per period without drift and across counter rollover.
- Protect a shared variable · Make a read-modify-write safe from interrupts, and safe to nest.
- Cooperative scheduler · Run periodic tasks from a table, the core of a super-loop.
- Smart lock: relock after 30 seconds · Relock automatically, with time arithmetic that survives the millisecond counter wrapping.