问题
I'm writing a multi-platform internal library in C++ that will eventually run on Windows, Linux, MacOS, and an ARM platform, and need a way to sleep for milliseconds at a time.
I have an accurate method for doing this on the ARM platform, but I'm not sure how to do this on the other platforms.
Is there a way to sleep with millisecond resolution on most platforms or do I have to special-case things for each platform?
回答1:
For Linux and Mac OS X you can use usleep
:
usleep(350 * 1000);
For Windows you can use Sleep
:
Sleep(350);
EDIT: usleep()
sleeps for microseconds, not milliseconds, so needs adjusting.
回答2:
boost::this_thread::sleep()
回答3:
usleep
provides microsecond resolution theoretically, but it depends on platform.
It seems to be obsolete on windows, so you should use QueryPerformanceCounter there (or write your compatibility layer).
P.S.: building program depending on sleep
s is often a way to disaster. Usually, what programmer really wants is waiting for some event to happen asynchronously. In this case you should look at waitable objects available at the platform, like semaphores or mutexes or even good ol' file descriptors.
回答4:
for timer you could use boost asio::deadline_timer, synchronously or asynchronously. you also could look into boost::posix_time for timer precision adjustment between seconds,milliseconds,microseconds and nanoseconds.
回答5:
Windows sleep() does provide millsecond precision, but nowhere near millisecond accuracy. There is always jitter, especially with small values on a heavily-loaded system. Similar problems are only to be expected with other non-real-time OS. Even if the priority of the thread calling sleep() is very high, a driver interrupt may introduce an extra delay at any time.
Rgds, Martin
来源:https://stackoverflow.com/questions/6134679/delaying-for-milliseconds-in-c-cross-platform