windows windows中c中的睡眠功能。是否存在精度更高的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/945320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 12:34:57  来源:igfitidea点击:

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

cwindowssleepprecisiondelay

提问by

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?

我想知道是否有人知道可以在 c 中的 windows 中使用的更好的睡眠函数,除了 Sleep(),它需要毫秒输入,并且只保证输入是经过的最短时间。我传递了 1 毫秒,但实际上延迟了 15-16 毫秒。有没有办法准确设置指定的睡眠时间?

采纳答案by Bill the Lizard

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.

不,不是真的。当你告诉你的程序休眠时,你就放弃了处理器,让操作系统决定下一步做什么。一旦操作系统获得控制权,它就会决定何时为您的程序提供另一片处理时间。这就是为什么您可以指定最小值,但不能保证操作系统会在任何特定时间返回到您的进程。

回答by Ana Betts

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

Sleep 只保证你的进程不会执行至少n毫秒,而不是它会正好休眠n毫秒。也许你想设置一个计时器?或忙等待(即在循环中轮询 QueryPerformanceCounter)。

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)

我会尽量避免这种方法(忙等待),除非您必须这样做,否则您正在消耗周期并且您正在阻止 CPU 进入较低的时钟速度(即消耗电池寿命)

回答by Joel Lucsy

回答by JaredPar

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.

不,Windows 上没有更好的睡眠功能,因为毫秒是可用的粒度级别。如果您想减少睡眠时间,则需要实现各种自旋锁。