time delay in C. usleep

Instead of sleeping for 20000 useconds, sleep for the time left till you want to run again, based on the call to clock_gettime

I.e:

usleep( lasttime+20000-now ); // But make sure you don't sleep when the result is negative

It is not that your code has a problem, but the actual call to sleep, reading the time, etc. takes time, and the system can't sleep for the exact time anyway unless it is a multiple of its exact clock cycle


Sleeping functions on non-realtime systems are not guaranteed to sleep the exact period specified; on a busy system, the process will be woken up only when its time slice begins. Or, as the man page puts it, "system activity may lengthen the sleep by an indeterminate amount".

The close-to-10ms amount sounds like the kern.hz frequency is lowered to 100, as some recommend for VM setups.

The classic workaround for this problem is the one offered by Ofir: instead of specifying a fixed sleeping interval, specify the remaining time to sleep. In average, your loop will run every 20ms, which is what you most likely want to achieve.