且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否有相当于 nanosleep 的 Windows?

更新时间:2023-11-28 23:43:16

可悲的是,这个问题没有好的答案.多媒体定时器可能是你能得到的最接近的——它们只允许你将周期设置为 1 毫秒,但是(感谢 timeBeginPeriod)它们实际上提供了大约 1 毫秒的精度,而其他大多数人通常只做大约 10-15 毫秒.

The sad truth is that there is no good answer to this. Multimedia timers are probably the closest you can get -- they only let you set periods down to 1 ms, but (thanks to timeBeginPeriod) they do actually provide precision around 1 ms, where most of the others do only about 10-15 ms as a rule.

还有很多其他候选人.乍一看,CreateWaitableTimerSetWaitableTimer 可能看起来最接近,因为它们的设置时间为 100 ns.不幸的是,至少在我的测试中,您不能真正依赖于接近该分辨率的任何地方.从长远来看,它们可能确实提供了***的可能性,因为它们至少可以让您指定小于 1 毫秒的时间,即使您目前无法依赖实现来提供(任何接近)该分辨率.

There are a lot of other candidates. At first glance, CreateWaitableTimer and SetWaitableTimer probably seem like the closest equivalent since they're set in 100 ns interals. Unfortunately, you can't really depend on anywhere close to that good of resolution, at least in my testing. In the long term, they probably do provide the best possibility, since they at least let you specify a time of less than 1 ms, even though you can't currently depend on the implementation to provide (anywhere close to) that resolution.

NtDelayExecution 似乎与 SetWaitableTimer 大致相同,只是它没有记录.除非您打算使用/测试未记录的函数,否则在我看来 CreateWaitableTimer/SetWaitableTimer 是更好的选择,只是在记录的基础上.

NtDelayExecution seems to be roughly the same, as SetWaitableTimer except that it's undocumented. Unless you're set on using/testing undocumented functions, it seems to me that CreateWaitableTimer/SetWaitableTimer is a better choice just on the basis of being documented.

如果您使用线程池,您可以尝试使用 CreateThreadPoolTimerSetThreadPoolTimer 代替.我还没有对它们进行足够的测试,无法确定它们真正提供的分辨率,但我并不特别乐观.

If you're using thread pools, you could try using CreateThreadPoolTimer and SetThreadPoolTimer instead. I haven't tested them enough to have any certainty about the resolution they really provide, but I'm not particularly optimistic.

计时器队列(CreateTimerQueueCreateTimerQueueTimer 等)是 MS 推荐的多媒体计时器替代品,但(至少在我的测试中)它们没有确实提供了比 Sleep 更好的分辨率.

Timer queues (CreateTimerQueue, CreateTimerQueueTimer, etc.) are what MS recommends as the replacement for multimedia timers, but (at least in my testing) they don't really provide much better resolution than Sleep.