nanosleep high CPU usage

Submitted by Anonymous
on July 14, 2009 - 11:30am

I noticed that a little test program which calls nanosleep is showing a huge difference in CPU usage when run on Linux machines with a kernel newer than 2.6.22.

#include
int main (void)
{
struct timespec sleepTime;
struct timespec returnTime;
sleepTime.tv_sec = 0;
sleepTime.tv_nsec = 1000;
while (1)
{
nanosleep(&sleepTime, &returnTime);
}
return 0;
}

(Yes, I realise this program does nothing)

If I compile this and run it on an openSUSE 10.3 machine (2.6.22.19-0.2-default), the program does not even show up on the process list generated by "top", indicating to me that it is using very little CPU time. If I run it on an openSUSE 11.1 machine (2.6.27.23-0.1-default), top shows the program taking 40% of the CPU time. Running on Fedora 9 (2.6.25-14.fc9.i686) and Fedora 10 also showed the same high CPU usage in "top".

Has there been a change in the kernel that affects this?

measurement

on
July 14, 2009 - 4:27pm

IIRC the scheduler was changed to more accurately measure the time (via the sched_clock), now time is measured in cpu clock ticks instead of timer ticks. processes giving up the cpu very fast can't 'fall between the cracks' any more.

also 2.6.25 and 2.6.27 contain the high resolution timers code. before everything would be rounded up to timer ticks. you should benchmark how many loops/s you get.

in 1000ns your cpu has about 3000 clock cycles (assuming 3GHz). a syscall can take several 100 clock cycles due to the context switches and handler code. 40% looks plausible.

Probably a limitation/bug in the old kernel

Anonymous (not verified)
on
July 15, 2009 - 10:15am

My guess is that your new kernel is doing exactly what you asked, and waking your process 1 million times a second. This is expected to chew up a fair amount of CPU.
Your old kernel probably rounded up to the nearest scheduling interval, and actually gave a delay three or four orders of magnitude larger than you requested.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.