Fun with timers (1)

So you’re building a C program that uses a 3rd party library which requires you to call a certain function every 10ms (10000 us)…

Seems simple right? Just do this:

....
usleep(10000);
....

This is supposed to sleep for 10000us. I’ve made a sample program that measures the difference between what we request and the actual time that usleep() sleeps.

The result is perhaps known but very annoying: linux sleeps for at least 10ms but regularly adds a random interval. On average I end up with 10200 us of sleep time but the highest value I observed in a little test run is 19313 us. One thing is guaranteed though, the sleep time is allways minimum 10000 us (as mentioned in the manpage ‘man usleep’).

The fact that this goes wrong is that the linux kernel is configured to run 1000 times/second (CONFIG_HZ=1000) and guess what, this program is not the only thing begging for cpu time. I’ve googled around and basically the advice is:

  1. Get a real RTOS –> That’s too easy
  2. Muck around with running process under SCHED_RR or SCHED_FIFO –> Been there done that but the policy mechanism in the Linux kernel has changed quite dramatically in the last years, set_rlimits is a useful tool though..

More to follow…