Unsigned timer wraparound and elapsed time in C
A free-running timer may return to zero while a program waits for a timeout. Comparing the raw current value with a previously computed absolute deadline can fail across that transition. For elapsed time, use the difference between two observations in the counter's unsigned arithmetic, and document how long observations may be separated.
The contract
The following example uses an exact-width unsigned counter. Converting the difference to uint32_t produces the modular result even on an implementation where operands promote to a wider int. The observation interval must be less than a complete counter period if that result is to equal actual elapsed ticks. This is not an arbitrary ordering relation between any two timestamps.
A small executable example
#include <stdint.h>
#include <assert.h>
#include <stdio.h>
static uint32_t elapsed(uint32_t now, uint32_t before) {
return (uint32_t)(now - before);
}
int main(void) {
assert(elapsed(2u, UINT32_MAX - 2u) == 5u);
assert(elapsed(10u, 10u) == 0u);
assert(elapsed(12u, 10u) == 2u);
puts("wraparound checked");
}
wraparound checked
Compiled with -Wall -Wextra -Werror and run under AddressSanitizer + UBSan.
Learning this for work or an interview? Lessons 1 and 2 of DSA for Firmware are free, with labs and C exercises. Start Lesson 1
What the example does not establish
The sample does not read an actual peripheral. The target may require a specific register access width, a latch sequence for split counters, or synchronization across clock domains. Check these separately. In a scheduling algorithm that compares arbitrary deadlines, a half-range convention is often needed; do not blindly reuse an elapsed-time calculation as a general deadline comparator.
Checks to add in your own project
Test the exact threshold, one tick below and one above it, with start values near the wrap boundary. Document what happens when a task misses observations for a whole counter period or when a device resets the counter. Include the tick frequency and maximum supported interval in the API contract. Measure elapsed time using the target's documented clock behavior rather than assumptions from a host test.
DSA for Firmware teaches it one real bug at a time.
- 28 lessons, each starting from a real firmware bug.
- 110 C exercises with tests, and a reference solution for every one.
- Lessons 1 and 2 are free. No sign-up.
Get the next article by email
One short email when a new article or free lesson is published. No spam. Unsubscribe at any time by replying to any email. See the privacy policy.