Section 18.1.4

Counter rollover and elapsed-time ambiguity

Definition

Counter rollover §6.21, also called wraparound, is the step in which a counter with a fixed number of bits passes its largest value and continues from zero. A counter of ww bits has 2w2^w values, so an 8-bit counter steps from 255 to 0. Elapsed-time ambiguity is the consequence for timing: two readings of such a counter show how far apart the two positions are, but not how many complete rounds of 2w2^w counts took place between the readings.

Where it fits

Main entry: Counter wraparound (§6.21).

The entry on counter wraparound gives the rule. Reducing a number modulo 2w2^w, the rule of unsigned modular arithmetic §4.16, means adding or subtracting 2w2^w until the result lies between 0 and 2w−12^w - 1. The end reading minus the start reading, reduced modulo 2w2^w, equals the true elapsed count exactly when the true elapsed count is less than 2w2^w.

One round of a 32-bit counter at 64,000,000 counts per second lasts 232/64,000,0002^{32} / 64{,}000{,}000 seconds, about 67.1 seconds. An interval of one round or longer is reported short by one or more whole rounds. The result is never negative, so a wrong result does not look wrong. A figure built from such a counter cannot show a time as long as one round, so ask what guarantees that every measured interval was shorter.

Questions answered

Why does casting the subtraction help, and when does it fail?

Casting the difference of two counter readings to an unsigned type with as many bits as the counter makes the result roll over as the counter does, so the elapsed count is right even when the counter passed zero between the readings, as long as less than one full round of the counter elapsed. Casting means converting a value to a stated type, and an unsigned type holds only whole numbers from zero upward. Take an 8-bit counter, which has 256 values, a start reading of 250 and an end reading of 5. Counting forward, six counts reach 0 and five more reach 5: the true elapsed count is 11. With the readings held in unsigned 8-bit variables start and end, the expression end - start in the language C gives −245-245, because C first converts operands narrower than its standard integer type int to int, a step called integer promotion §4.18. The cast (uint8_t)(end - start) converts −245-245 to the unsigned 8-bit type, which holds the values 0 to 255. The C standard defines that conversion as adding 256 until the value fits: −245+256=11-245 + 256 = 11. For a 32-bit counter in unsigned 32-bit variables, on a machine whose int has 32 bits, the subtraction already rolls over and the cast changes nothing.

The cast fails in three cases.

Related entries: Unsigned modular arithmetic (§4.16), DWT cycle counter (§6.20), Integer promotion and conversion (§4.18), Serial-number arithmetic and the half-range ambiguity (§19.3.4), Clock conversion, resolution, and accuracy (§18.1.2). Further reading: [78].