Raceimaztion
Raceimaztion

Reputation: 9624

Delaying for milliseconds in C++ cross-platform

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?

Upvotes: 1

Views: 10102

Answers (5)

Martin James
Martin James

Reputation: 24847

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

Upvotes: 1

t.g.
t.g.

Reputation: 1749

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.

Upvotes: 1

elder_george
elder_george

Reputation: 7879

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

Upvotes: 2

trojanfoe
trojanfoe

Reputation: 122381

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.

Upvotes: 7

ildjarn
ildjarn

Reputation: 62975

boost::this_thread::sleep()

Upvotes: 7

Related Questions