Sleep operation in C++ on OS X

EDIT 2017: C++11 sleep_for is the right way to do this. Please see Xornad's answer, below.


C++03:

Since Mac OS X is Unix-based, you can almost always just use the standard linux functions!

In this case you can use usleep (which takes a time in microseconds) and just multiply your milliseconds by 1000 to get microseconds.

#include <unistd.h>
int main () {
    usleep(1000); // will sleep for 1 ms
    usleep(1); // will sleep for 0.001 ms
    usleep(1000000); // will sleep for 1 s
}

For more info on this function, check out the Linux man page:

http://linux.die.net/man/3/usleep


If you have C++11 support in your compiler, you can use the sleep_for and avoid having to use an OS specific API. (http://en.cppreference.com/w/cpp/thread/sleep_for)

#include <thread>
#include <chrono>

int main()
{
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    return 0;
}

Tags:

C++

Macos

Sleep