When I was writing micro_timer first thing I tried was a C implementation of the sleep function.
I’ve tried almost everything, from setting a timeout to select and kevent to Posix timer_* functions, none of them worked reliably.
From my measurements, without spinlocks, you can’t get consistent sub-millisecond timings, to the point that waiting 1 million times for 1 microsecond (should be a second) takes almost 2 seconds.
The graph below shows the average difference between the timeout and the time it actually took to return.
The results are computed from 50 thousands samples, the timeout was set randomly from 1 to 65.535 microseconds (65ms).
The average deviation for the C implementation is 2.509ms, 11.4%.
But the worst case is 10x off.
The three implementation tested are
- C uses
selectwith a timeout - Ex0 waits timeout - 1ms and loops for a maximum of 1ms
- Ex1 waits timeout - 2ms and loops for a maximum of 2ms
If you don’t need consistent absolute precision, any of the C implementations is good enough and they roughly work the same way.























