views:

2333

answers:

5

I was wondering if anyone knew of a better sleep function that could be used in windows in c, other than Sleep(), which takes a millisecond input and only guarantees that the input is the minimum amount of time that elapses. I am passing in 1 millisecond, but actually getting a 15-16 millisecond delay. Is there any way to accurately set a specified sleep time?

A: 

Look into Multimedia Timers.

Joel Lucsy
I believe multimedia timers still use milisecond granuality though
JaredPar
+1  A: 

No, there isn't a better sleep function on Windows because milliseconds is the level of granularity available. If you want to sleep for less time you'll need to implement a spin lock of sorts.

JaredPar
+2  A: 

No, not really. When you tell your program to sleep, you're giving up the processor and letting the operating system decide what to do next. Once the operating system is in control, it decides when to give your program another slice of processing time. This is why you can specify a minimum, but there's no guarantee that the OS will get back to your process at any particular time.

Bill the Lizard
A: 

Sleep only guarantees that your process will not execute for at least n milliseconds, not that it will sleep exactly n milliseconds. Maybe you want to set up a timer? Or busy wait (i.e. poll QueryPerformanceCounter in a loop).

I'd try to avoid this approach (busy wait) unless you have to though, you're burning cycles and you're stopping the CPU from being put into lower clock speeds (i.e. burning battery life)

Paul Betts