A free-running digital counter with modulus shows only the residue of elapsed ticks. If two observations differ by a true interval , their modular difference is congruent to and is the unique representative in , proving the displayed identity. It handles a wrap between observations without a conditional branch. A complete elapsed modulus is indistinguishable from zero, so the interval bound is essential. For a -bit timer at frequency , the wrap period is , and unsigned integer arithmetic in C can implement the difference directly on an appropriate type.
A 32-bit free-running timer operates modulo . If its previous reading is , and the actual elapsed count is with , the new reading is . The modulo-counter elapsed-time identity therefore gives
Unsigned integer arithmetic in C reduces the subtraction modulo , so the identity remains valid when a wrap occurs between pulses. For example, readings and give 16,000 ticks, hence one millisecond, rather than a negative interval.[ref]
At the specified clock rate, the true wrap period is seconds. The printed 256 seconds is inconsistent with the other two specifications. The implementation uses the stated 32-bit width and 16 MHz rate. Assuming consecutive handled pulses are less than 256 seconds apart is a sufficient conservative bound; the exact allowable bound is less than 268.435456 seconds.
This calculation requires less than one entire timer modulus of elapsed ticks between successive stored timestamps. If a whole wrap or several wraps elapse, identical register readings cannot reveal how many occurred; an overflow counter or an independent longer-range clock would be needed. Also assume pulse events are not lost and interrupt latency is constant or sufficiently small for the required accuracy: timestamps read in software measure handler-to-handler intervals, not perfect hardware capture times. Conversion to milliseconds occurs after modular subtraction, so separately rounded absolute timestamps cannot corrupt the wrap calculation.