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.

Leave a Comment