Sleep function in C++

Use std::this_thread::sleep_for:

#include <chrono>
#include <thread>

std::chrono::milliseconds timespan(111605); // or whatever

std::this_thread::sleep_for(timespan);

There is also the complementary std::this_thread::sleep_until.


Prior to C++11, C++ had no thread concept and no sleep capability, so your solution was necessarily platform dependent. Here's a snippet that defines a sleep function for Windows or Unix:

#ifdef _WIN32
    #include <windows.h>

    void sleep(unsigned milliseconds)
    {
        Sleep(milliseconds);
    }
#else
    #include <unistd.h>
    
    void sleep(unsigned milliseconds)
    {
        usleep(milliseconds * 1000); // takes microseconds
    }
#endif

But a much simpler pre-C++11 method is to use boost::this_thread::sleep.


You'll need at least C++11.

#include <thread>
#include <chrono>

...

std::this_thread::sleep_for(std::chrono::milliseconds(200));

On Unix, include #include <unistd.h>.

The call you're interested in is usleep(). Which takes microseconds, so you should multiply your millisecond value by 1000 and pass the result to usleep().