On Feb 2, 2007, at 11:38 PM, Greg wrote: On Feb 2, 2007, at 11:05 PM, Ed Wynne wrote: Date: February 2, 2007 10:28:08 PM EST Subject: Sleeping in nanos
Is there a way on OS X to sleep for 1000 nanoseconds without causing 65% CPU usage? I have tried nanosleep and clock_sleep (using TIME_RELATIVE and a REALTIME_CLOCK), and both seem to simply cause a busy loop.
Assuming an instruction takes one cycle (some do, lots don't) and a 2Ghz CPU, each instruction will take .5ns. That means the CPU can run 2000 instructions, at most, while your sleeping for 1us.
Oops, bad math there... hehehe... I'm an engineer, not a mathematician! Good thing I'm not sending probes to Mars or anything important like that 8) Given that any kind of sleep function will be a syscall into the kernel and invoke the scheduler, I'd be willing to bet it takes a lot more than 2000 instructions just to put yourself to sleep and then wake back up. Your 65% CPU usage is probably indicative of this. It is taking longer to setup and recover from sleep than your spending sleeping.
So then why do I barely see 1% CPU utilization on linux?
There are the obvious reasons. The syscall overhead on linux is likely less, the scheduler overhead is likely less, etc. This example, like most other similar NULL syscall microbenchmarks, shows linux in a favorable light.
A non-obvious reason might be that linux is also sleeping longer. A longer sleep-to-wake duty cycle makes for less CPU usage. The mechanics of sleep setup and wakeup are one factor, but the length of sleep is another. The OS X scheduler might actually be doing more of the right thing(tm) than the linux scheduler. If history hasn't lost its sense of irony, you'd probably consider this a performance problem and blame OS X for being worse. I can't say this is happening, but I'd have a hard time blaming a 65% vs 1% CPU usage on just syscall overhead. Thats just a bit too much efficiency for my cynical gut to buy.
I'd be curious to see how many sleeps actually occurred over a 1 second period on OS X vs linux. I'd do the test myself, but I'm fresh out of linux boxen at the moment.
-Ed
|