Section 6.21

Counter wraparound

Definition

Counter wraparound is the return of a fixed-width counter to zero after its largest value. A counter ww bits wide holds M=2wM = 2^{w} values, 0 to M−1M - 1; one step after M−1M - 1 it shows 0 and keeps counting. A reading therefore shows the true count only modulo MM: the remainder after dividing the true count by MM. 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 MM positions. Subtracting the earlier reading from the later one, and adding MM 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.

  1. Model. The counter counts up by one per tick. If CC is the true number of ticks since it started, the reading is CmodMC \bmod M.

  2. Subtract modulo MM. For an earlier reading aa and a later reading bb, compute d=(b−a)modMd = (b - a) \bmod M, a number from 0 to M−1M - 1. The true elapsed count Δ\Delta equals d+kMd + kM for some whole number k≥0k \ge 0, the number of extra full turns.

  3. Match the arithmetic to the width. In C, arithmetic on an unsigned type at least as wide as int is done modulo 2N2^{N}, where NN is the type’s width in bits, as the unsigned modular arithmetic §4.16 entry explains. For a 32-bit counter read into uint32_t variables, b - a is already dd. For a counter narrower than its variable, mask the result, for example (b - a) & 0xFFFFFF for 24 bits. For variables narrower than int, such as uint16_t with a 32-bit int, C first converts both operands to int (integer promotion §4.18), so b - a can be negative; convert the result back with (uint16_t)(b - a).

  4. Rule out extra turns. Only k=0k = 0 gives Δ=d\Delta = d, and the readings never reveal kk.

Establishing kk.

Other counters. A counter that counts down, such as the SysTick timer built into Cortex-M processors, gives d=(a−b)modMd = (a - b) \bmod M. A counter that restarts from a reload value RR counts R,R−1,…,0R, R - 1, \dots, 0, so its period is P=R+1P = R + 1, which is usually not a power of two. A mask then gives wrong answers, and the subtraction must be done modulo PP explicitly: for a down-counter, d=a−bd = a - b if a≥ba \ge b, and d=a−b+Pd = a - b + P 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 M/2M/2 apart, in either order, then 0<d<M/20 < d < M/2 means that bb is later and d>M/2d > M/2 means that aa is later; at exactly d=M/2d = M/2 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 w=4w = 4, M=24=16M = 2^{4} = 16, and the counter shows 0 to 15. The readings are a=14a = 14 and b=3b = 3. Then b−a=3−14=−11b - a = 3 - 14 = -11, and −11+16=5-11 + 16 = 5, so d=5d = 5. Counting forward confirms it: 14, 15, 0, 1, 2, 3 is 5 steps. But 21 steps, 5+165 + 16, 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 232=4,294,967,2962^{32} = 4{,}294{,}967{,}296: 256−4,294,967,040+4,294,967,296=512256 - 4{,}294{,}967{,}040 + 4{,}294{,}967{,}296 = 512. 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 500−65,000=−64,500500 - 65{,}000 = -64{,}500, which is wrong. Converted back, (uint16_t)(b - a) is −64,500+65,536=1,036-64{,}500 + 65{,}536 = 1{,}036, 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 a=60,000a = 60{,}000 and b=5,000b = 5{,}000, so d=(5,000−60,000)mod65,536=10,536d = (5{,}000 - 60{,}000) \bmod 65{,}536 = 10{,}536, 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 ±1%\pm 1\%, so the true time lies between 75/1.01≈74.25775 / 1.01 \approx 74.257 ms and 77/0.99≈77.77877 / 0.99 \approx 77.778 ms. Treating the 1 MHz counter’s own rate as exact gives L=74,258L = 74{,}258 and U=77,777U = 77{,}777 ticks (74,257.4 rounded up and 77,777.8 rounded down, because Δ\Delta is a whole number), a window 3,519 ticks wide, far narrower than 65,536. Then Δ=L+((d−L)modM)=74,258+((10,536−74,258)mod65,536)=74,258+1,814=76,072\Delta = L + ((d - L) \bmod M) = 74{,}258 + ((10{,}536 - 74{,}258) \bmod 65{,}536) = 74{,}258 + 1{,}814 = 76{,}072, which is at most UU. The counter wrapped once, and the interval lasted 76.072 ms.

Stated precisely

Let ww be the counter width in bits and M=2wM = 2^{w}. Let aa and bb be two readings of the same counter, taken in that order, and let Δ\Delta 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 b=(a+Δ)modMb = (a + \Delta) \bmod M, so d=(b−a)modMd = (b - a) \bmod M satisfies Δ=d+kM\Delta = d + kM for some whole number k≥0k \ge 0. Hence d=Δd = \Delta if and only if 0≤Δ<M0 \le \Delta < M. The tick rate does not enter this statement: Δ\Delta is a number of ticks, however they are spaced in time.

Enclosure. If independent evidence gives L≤Δ≤UL \le \Delta \le U with U−L<MU - L < M, then the only possible value is Δ=L+((d−L)modM)\Delta = L + ((d - L) \bmod M), and the readings are consistent only if this value is at most UU.

Ordering. Let ss be the true signed separation of the two events, positive when bb was taken later. If |s|<M/2|s| < M/2, then s=ds = d when d<M/2d < M/2, and s=d−Ms = d - M when d>M/2d > M/2.

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 b=(a+Δ)modMb = (a + \Delta) \bmod M. 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.

  1. Both readings come from the same counter, which counts up by one per tick and was not reset or written to between the readings.

  2. The subtraction is done modulo the counter’s period M=2wM = 2^{w}, where ww is the counter’s width in bits: in an unsigned type of exactly ww bits, or with the result masked to ww bits, and, in C, converted back to the narrow type when the operands were promoted to int.

  3. 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.

  4. The true elapsed count is known, from evidence other than the two readings, to be less than MM.

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 d+kMd + kM for k=0,1,2,…k = 0, 1, 2, \dots, where dd 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 M/2M/2.

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).