Sleep function in c in windows. Does a function with better precision exist?

a 夏天 提交于 2019-12-23 18:16:00

问题


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?


回答1:


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.




回答2:


Look into Multimedia Timers.




回答3:


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)




回答4:


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.



来源:https://stackoverflow.com/questions/945320/sleep-function-in-c-in-windows-does-a-function-with-better-precision-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!