Modulo-counter elapsed-time identity (source code)

= Modulo-counter elapsed-time identity
{title2=$((p+d)\bmod M-p)\bmod M=d\quad(0\leq d<M)$}

A free-running <digital counter> with modulus $M$ shows only the residue of elapsed ticks. If two observations differ by a true interval $d<M$, their modular difference is congruent to $d$ and is the unique representative in $\{0,\ldots,M-1\}$, 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 $w$-bit timer at frequency $f$, the wrap period is $2^w/f$, and <unsigned integer arithmetic in C> can implement the difference directly on an appropriate type.