strange long latency around a usleep call


New Member
Hi, I have a very simple hello world program that prints hello world, and then uses a pair of gettimeofday() to bracket around a usleep(50) call. I will then printf if the elapsed time between the two gettimeofday() calls is greater than 5ms.

When running on a Linux Vmware VM, and even on a native Linux laptop, I noticed that sometimes I would get elapsed time from 5ms to 10ms. I see much less printf on the native Linux laptop compared to the VMware, but it still does show up. On the native Linux laptop, the elapsed time is even up to 20ms, but I see much less printf than on the VMWare.

Why is this happening? Neither the VMware or the native Linux laptop is very busy at all.

How to mitigate this?

Thanks any insight.


Well-Known Member
Are you sure it’s not the gettimeofday function calls that are causing the overhead??

Also - calling any function invokes a little overhead, because of the time taken to set up the stack frames etc. So aside from the delay you’ve specified in your usleep, there is the time taken to execute the two gettimeofday calls to take into consideration too.

The other thing to consider is that Linux is not a real time operating system. So perhaps the variation is partially due to something like cpu scheduling?!

Off the top of my head - Have you tried using the strace command to view any system calls that are being used by your program?
Perhaps try :
strace -r -t /path/to/executable
That might show where some of the delays are coming from.... Perhaps some of the underlying system calls used by functions you’ve called in your program are causing the variations in execution time?!


New Member
Thank you for your reply. Really appreciate.
I will definitely try stracing it. The timeofday() and usleep() is in an infinite while loop, so it may get a little noisy when doing strace.
But it is hard to imagine timeofday() being delayed in the millisecond range. It feels more like the process being swapped out and didnt get swapped back in for that long.

Will rebuilding the kernel for preemption mode be worth a try? It is now compiled as Desktop mode.

Members online

Latest posts