Is there a Windows equivalent of nanosleep?

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.

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 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.

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.

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.

Leave a Comment