Definition
Counter wraparound is the return of a fixed-width counter to zero after its largest value. A counter bits wide holds values, 0 to ; one step after it shows 0 and keeps counting. A reading therefore shows the true count only modulo : the remainder after dividing the true count by . Wraparound, also called rollover, is the normal behavior of hardware timers and of unsigned integers in C. It is not an error, but it limits what two readings can tell.
The idea
A 12-hour clock shows 11 o’clock, and later it shows 3 o’clock. The obvious answer is that 4 hours passed, with the hour hand crossing 12 once. But after 16 hours, or 28, the clock would show the same two readings. The clock face cannot say how many full turns the hand made. Someone who also knows that less than 12 hours passed can rule out every answer except 4.
A hardware counter is such a clock face with positions. Subtracting the earlier reading from the later one, and adding when the result is negative, gives the forward distance between them. That distance is the elapsed count only if less than one full turn passed, and that fact must come from elsewhere: a bound on the interval, a count of the wraps, or a second clock.
How it works
Computing an elapsed count.
Model. The counter counts up by one per tick. If is the true number of ticks since it started, the reading is .
Subtract modulo . For an earlier reading and a later reading , compute , a number from 0 to . The true elapsed count equals for some whole number , the number of extra full turns.
Match the arithmetic to the width. In C, arithmetic on an unsigned type at least as wide as
intis done modulo , where is the type’s width in bits, as the unsigned modular arithmetic §4.16 entry explains. For a 32-bit counter read intouint32_tvariables,b - ais already . For a counter narrower than its variable, mask the result, for example(b - a) & 0xFFFFFFfor 24 bits. For variables narrower thanint, such asuint16_twith a 32-bitint, C first converts both operands toint(integer promotion §4.18), sob - acan be negative; convert the result back with(uint16_t)(b - a).Rule out extra turns. Only gives , and the readings never reveal .
Establishing .
A design bound: the interval is known to be at most seconds, one tick less than the period of seconds, for a counter that ticks times per second. An interval shorter than the period by less than one tick is not enough, because it contains ticks when the first reading comes just before a tick and the second just after one. The bound must hold for the real elapsed time, including any time the measuring code spent preempted or halted.
Counting the wraps: an interrupt handler §6.12 adds one to a software variable at each wrap, extending the counter, for example to 64 bits (the wrap count times plus the hardware reading); operating-system tick counters and monotonic clocks §9.35 are commonly built this way. The two parts cannot be read in one atomic operation §9.8, so code reads the wrap count, the hardware counter and the wrap count again, and repeats if the two wrap counts differ. Code running with interrupts §6.11 disabled must also check the timer’s pending wrap flag.
An enclosure check: a second clock that does not wrap during the interval, with a rate known to within a stated tolerance, bounds the elapsed count: . If , at most one value lies in that range, and that value is . If none does, the readings contradict each other and the measurement is rejected.
Other counters. A counter that counts down, such as the SysTick timer built into Cortex-M processors, gives . A counter that restarts from a reload value counts , so its period is , which is usually not a power of two. A mask then gives wrong answers, and the subtraction must be done modulo explicitly: for a down-counter, if , and otherwise.
Ordering two readings. Deciding which reading is later needs a stricter bound than measuring the time between them. If the two events are known to be less than apart, in either order, then means that is later and means that is later; at exactly both orders fit. A portable C test for a 32-bit counter computes d = b - a in uint32_t and checks d != 0 && d < 0x80000000u. The common shortcut (int32_t)(b - a) > 0 relies on implementation-defined behavior §4.13, because C leaves the conversion of an unsigned value too large for the signed type to the compiler. The same half-range rule governs serial-number arithmetic §19.3.4 for sequence numbers that wrap.
Worked example
A 4-bit counter. With , , and the counter shows 0 to 15. The readings are and . Then , and , so . Counting forward confirms it: 14, 15, 0, 1, 2, 3 is 5 steps. But 21 steps, , also lead from 14 to 3, and so do 37. Only the knowledge that the interval was shorter than 16 ticks makes the answer 5.
A 32-bit counter in C. With uint32_t readings a = 0xFFFFFF00 (4,294,967,040) and b = 0x00000100 (256), b - a is computed modulo : . That is 256 counts up to the wrap and 256 after it.
A 16-bit counter and integer promotion. With uint16_t readings a = 65000 and b = 500 on a processor whose int has 32 bits, both operands become int, and b - a is , which is wrong. Converted back, (uint16_t)(b - a) is , the true count: 536 counts up to the wrap and 500 after it.
An enclosure check. A 16-bit counter ticks at 1 MHz (megahertz, one million ticks per second), so it wraps every 65,536 ticks, that is every 65.536 milliseconds (ms). Its readings are and , so , and the candidates are 10,536, 76,072, 141,608 ticks and so on. A millisecond counter, read at the same two moments, advanced by 76. Each of its readings is rounded down to a whole millisecond, so it measured between 75 and 77 of its milliseconds. Its oscillator is accurate to , so the true time lies between ms and ms. Treating the 1 MHz counter’s own rate as exact gives and ticks (74,257.4 rounded up and 77,777.8 rounded down, because is a whole number), a window 3,519 ticks wide, far narrower than 65,536. Then , which is at most . The counter wrapped once, and the interval lasted 76.072 ms.
Stated precisely
Let be the counter width in bits and . Let and be two readings of the same counter, taken in that order, and let be the true number of ticks between them. If the counter counts up by one per tick and nothing reset it or wrote to it between the readings, then , so satisfies for some whole number . Hence if and only if . The tick rate does not enter this statement: is a number of ticks, however they are spaced in time.
Enclosure. If independent evidence gives with , then the only possible value is , and the readings are consistent only if this value is at most .
Ordering. Let be the true signed separation of the two events, positive when was taken later. If , then when , and when .
Limits and common mistakes
Two readings never reveal the number of extra turns. A measurement that may have lasted longer than one period cannot be repaired afterwards from its readings.
The bound must cover the worst case, not the usual case. Code that usually takes 1 ms can be preempted, wait for a lock or be halted by a debugger for longer than a period. Equal readings mean either no time or a whole number of turns.
A width mismatch gives a wrong number: subtracting the 24-bit readings 0xFFFFF0 and 0x000010 in 32-bit arithmetic without the mask gives 4,278,190,112 instead of 32.
Signed timestamps are not a fix. Subtracting timestamps held in a signed type can cause signed integer overflow §4.15, which is undefined behavior §4.12 in C: the compiler may assume it never happens and produce code that behaves unpredictably.
A reset of the counter or a write to it between the readings breaks the relation . A change of tick rate alone does not break it. On some timers, however, the reconfiguration that changes the rate also resets the count, and that reset does. A rate change breaks the conversion between ticks and time instead: the elapsed time is no longer the count divided by one rate, and a design bound in seconds must be multiplied by the highest rate in force during the interval to bound the count. Readings from two different counters are never subtracted from each other, even when both have the same width.
Questions answered
When is unsigned subtraction a valid elapsed-count computation?
Unsigned subtraction of two counter readings, the later minus the earlier, gives the elapsed count exactly when four conditions hold.
Both readings come from the same counter, which counts up by one per tick and was not reset or written to between the readings.
The subtraction is done modulo the counter’s period , where is the counter’s width in bits: in an unsigned type of exactly bits, or with the result masked to bits, and, in C, converted back to the narrow type when the operands were promoted to
int.The period is a power of two. A counter that restarts from a reload value needs explicit subtraction modulo its period instead of a mask.
The true elapsed count is known, from evidence other than the two readings, to be less than .
Under these conditions the result is correct even when the counter wrapped once, because modular subtraction adds back the one missing period. Without the fourth condition, the readings fit every elapsed count for , where is the subtraction’s result. The evidence for the fourth condition is a design bound on the interval, a count of the wraps, or an enclosure check against a second clock. A change of tick rate between the readings does not affect the subtraction, which counts ticks; it matters only where seconds are converted to ticks or ticks to seconds, as in a design bound or an enclosure check. Deciding which of two readings is later needs the stricter bound .
Related entries: Unsigned modular arithmetic (§4.16), DWT cycle counter (§6.20), Monotonic clock (§9.35), Integer promotion and conversion (§4.18), Signed integer overflow (§4.15).