Full name: Data Watchpoint and Trace (DWT) cycle counter.
Definition
The DWT cycle counter is a 32-bit hardware counter in many Arm Cortex-M processors that adds one on every cycle of the processor clock, the signal that paces the processor’s instructions. DWT stands for Data Watchpoint §14.29 and Trace, the debug unit that contains the counter; Arm names its register DWT_CYCCNT. Software reads the counter before and after a piece of code and subtracts the first reading from the second to get the number of clock cycles that passed. Dividing that number by the clock frequency turns it into seconds.
The idea
A developer wants to know how long a function takes on a microcontroller §6.1 and expects a few microseconds. The operating system’s clock tick, often 1 millisecond long, is far too coarse: the function usually starts and ends within one tick. A cycle counter resolves a single clock cycle. At a processor clock of 64 MHz (megahertz, millions of cycles per second), one cycle lasts s, which is 15.625 ns (nanoseconds). Reading the counter is one load instruction from a fixed address, so it costs only a few cycles.
Picture a trip odometer that advances by one for every clock cycle: two readings and a subtraction give the distance between them, and after counts it rolls over to zero. The picture stops being accurate in one respect. An odometer moves whenever the car moves, but the cycle counter stops whenever the processor clock stops or a debugger halts the processor, although real time goes on.
How it works
The counter belongs to the processor’s debug hardware, so software must switch it on. On a processor of the Armv7-M architecture, such as the Cortex-M3, Cortex-M4 §6.3 or Cortex-M7:
Enable the trace units. Set bit 24,
TRCENA(trace enable), ofDEMCR, the Debug Exception and Monitor Control Register (address0xE000EDFC). WhileTRCENAis 0, reads of the DWT registers return unknown values, so this step comes before any DWT register is read.Check that the counter exists. Bit 25 of the DWT control register
DWT_CTRL(address0xE0001000), namedNOCYCCNT, reads 1 when there is no cycle counter. The architecture makes the counter optional, and processors of the smaller Armv6-M architecture, such as the Cortex-M0, have none. The DWT unit itself is optional as well; the processor’s ROM table, a table of the debug components present, records whether it exists.Clear the count, which is optional because only differences matter. Write 0 to
DWT_CYCCNT(address0xE0001004); its value after reset is unknown.Start counting. Set bit 0,
CYCCNTENA(cycle counter enable), ofDWT_CTRL.
Some implementations also lock the debug registers against writes until software opens a software lock, which must then happen before the steps that write them; the processor’s technical reference manual says whether such a lock exists. Only privileged code, meaning code at the higher privilege level §6.10 such as an operating-system kernel, may access these registers; an access from unprivileged code causes a fault exception.
To measure, store the counter value as before the code and as after it, both in 32-bit unsigned variables. The cycle count is , computed in 32-bit unsigned arithmetic, which is right even if the counter rolled over once in between; the counter wraparound §6.21 entry explains why. Dividing the cycle count by the clock frequency , in cycles per second, gives seconds.
The difference counts every cycle between the two reads: the measured code, the read itself, interrupt handlers §6.12 and other threads that ran in between, and cycles in which the processor waited, for example for slow flash memory §6.6. The cost of the reads is instrumentation overhead §11.32. Reading the counter twice in a row measures it, and that count is subtracted from each measurement.
The counter stops in two situations. The Armv7-M architecture states that it does not count while a debugger holds the processor halted. It also stops whenever the processor clock stops, since it counts that clock’s cycles. Whether that clock runs while the processor sleeps, for example after the WFI (wait for interrupt §6.11) instruction, depends on the chip and on the sleep mode.
Worked example
Wrap period. The counter has values. At MHz it returns to the same value after s. At 16 MHz the period is s, about 4.5 minutes; at 480 MHz it is s. One subtraction of two readings is correct only for intervals shorter than this period.
One measurement. At 64 MHz the first reading is and the second is : the counter rolled over in between. In 32-bit unsigned arithmetic, cycles. Suppose two reads in a row differ by 3 cycles on this processor (a value assumed for the example; it must be measured on the real chip). The code then took cycles, which is s = 156.203125 microseconds.
Converting with an imperfect clock. If the 64 MHz clock comes from a clock source §6.18 built on a quartz crystal accurate to ppm (parts per million), the true frequency lies between and 64,001,280 cycles per second. The 156.2-microsecond result is then uncertain by at most microseconds, which is negligible. A 60-second interval would be uncertain by up to s.
Stated precisely
Let be the counter width in bits ( for DWT_CYCCNT) and let be the processor clock frequency in cycles per second. While the counter counts at a constant , it returns to the same value every Let and be two readings taken in that order, and let be the number of cycles the counter actually counted between them. The value , which 32-bit unsigned subtraction computes, equals exactly when . The elapsed time is then seconds.
These statements depend on five assumptions.
Enabled: the counter exists, and
TRCENAandCYCCNTENAstayed set during the whole interval.Undisturbed: neither software nor a debugger wrote to the counter between the two readings.
Running: the processor was not halted by a debugger and its clock did not stop; otherwise is smaller than the elapsed time multiplied by .
Known rate: did not change during the interval, and its value is known to within the tolerance of the clock source.
Short: fewer than cycles passed, which at 64 MHz means less than 67.108864 s.
Limits and common mistakes
The counter measures elapsed cycles, not the cost of one function alone. Interrupt handlers, other threads and waiting time inside the interval all count, so one measurement is a response time §9.32, the time from start to finish including interruptions, not an execution time, the time spent running the code itself. Disabling interrupts removes these disturbances but changes the system being measured. Repeated measurements do not give a worst-case execution time §9.33 either: the longest time the code can ever take needs an analysis of its longest possible path, not the longest observed run.
Fine resolution is not accuracy. One count lasts 15.625 ns at 64 MHz, but the result still carries the error of the clock source, the cost of the reads, and the rounding of a duration to whole cycles, which the counter quantization §11.35 entry treats. Nor are cycles instructions: one load from flash memory with wait states takes several cycles.
The counter is not a wall clock §9.36. It stops during a debugger halt and may stop during sleep, while a low-frequency timer that runs from its own clock keeps counting through both. The two counters belong to different clock domains §13.29, and their readings cannot be subtracted from each other.
Other users can change the counter, because it is shared debug hardware. A debugger may reset or disable it. The software of J-Link §6.27 debug probes, devices that connect a computer to a chip’s debug interface, by default clears the debug enable bits, including TRCENA, when a debug session closes, so that the chip can reach its low-power modes; an application that enabled the counter earlier can no longer rely on it. The J-Link setting SetDbgPowerDownOnClose = 0 keeps the bits set.
Questions answered
How often does a finite-width counter wrap at the chosen CPU frequency?
A counter that is bits wide and advances once per clock cycle wraps, meaning it passes its largest value and starts again from zero, every seconds, where is the clock frequency in cycles per second. For the 32-bit DWT (Data Watchpoint and Trace) cycle counter of an Arm Cortex-M processor at 64 MHz (megahertz), this is s, about 67 seconds. At 16 MHz it is about 268 s, and at 480 MHz about 8.9 s. A 24-bit counter that advances 32,768 times per second wraps every s.
The formula counts only time during which the counter advances at the rate . In real time the period is longer if the counter pauses, for example during a debugger halt or while the processor clock is stopped in sleep. The period also limits what one subtraction of two readings can measure: the subtraction gives the right count only when the counter advanced fewer than times between the readings, which an interval at least one cycle shorter than the period guarantees.
Related entries: Counter wraparound (§6.21), Counter quantization (§11.35), Worst-case execution time (WCET) (§9.33), RTC versus cycle counter (§6.19), SWD (§6.25). Further reading: [5, 81].