Sleep function in C++

c++

Question

Is there a function like Sleep(time); that pauses the program for X milliseconds, but in C++?

Which header should I add and what is the function's signature?

1
49
9/9/2018 9:11:37 PM

Use std::this_thread::sleep_for:

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.

87
6/8/2019 12:19:35 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon