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?
-
You say you want a guaranteed minimum, but from your example it sounds like you actually want a guaranteed exact amount of time (or possibly a guaranteed maximum). – Evan Shaw Jun 03 '09 at 16:11
-
The sleep() function only wakes up every 18ms – Martin Beckett Jun 04 '09 at 02:29
-
See related http://stackoverflow.com/questions/85122/sleep-less-than-one-millisecond – harpo Jun 03 '09 at 15:14
4 Answers
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.

- 398,270
- 210
- 566
- 880
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)

- 73,868
- 16
- 141
- 209
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.

- 733,204
- 149
- 1,241
- 1,454