Archive for July 2011

nanosleep(), usleep() and sleep() Precision Tests

Working on some Amazon EC2 benchmarks I run through few problems of having my processes to run with a high time precision where a more than 1ms shift between operations is not acceptable.

My program accumulates work time and sleep time, ideally, it would work for time t, sleeps for T - t microseconds and loop again. The problem is that in the sleep routine, a shift of few microseconds can be accumulated to become a shift of milliseconds after few loops.

After investigating the problem a little, I did some tests on how precise are the sleep functions in C, here is the code I used to test nanosleep(), usleep() and sleep().



Running these tests on my machine with Fedora 15 gives me these results :


As you can see, there is always an overhead of 100µs to 180µs, a call to printf inside the function will take about 70 µs more to execute. The call to the function itself (the nsleep function) takes at worst 1µs. With this accumulation of  microseconds, a program would get to a state where it is late by some milliseconds after a dozen of iterations and calls to these sleep functions.

On the other side gettimeofday() behaves pretty well considering precision, the benchmark below (found here) gives the following results:

$ ./gettimeofday_benchmark
50000000 cycles in 2315879542 ns = 46.317591 ns/cycle
Which is satisfying for its precision.

A solution (that is not applicable in all cases) is to have a global program independent clock regarding to which the sleep period is adapted. For example instead of waiting T - t microseconds, one will use every second tick on the system as a landmark, and thus any microseconds lost in the last loop iteration are discarded in the next one since the wait time is not dependent on the time the loop has started.


Swedish Greys - a WordPress theme from Nordic Themepark. Converted by LiteThemes.com.