97

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Does this answer your question? [Sleep for milliseconds](https://stackoverflow.com/questions/4184468/sleep-for-milliseconds) – Cris Luengo Jul 12 '21 at 15:37

10 Answers10

139

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.

ad absurdum
  • 19,498
  • 5
  • 37
  • 60
GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • 1
    Hint: this_thread::sleep_for etc. is using singletons and therefore introduces STB_GNU_UNIQUEs, which - if used in a shared lib - will prevent your lib from being able to unload. – user1050755 Mar 20 '20 at 05:25
62

You'll need at least C++11.

#include <thread>
#include <chrono>

...

std::this_thread::sleep_for(std::chrono::milliseconds(200));
Jostein Topland
  • 990
  • 8
  • 16
  • 13
    The C++ committee is really strange if they think this is an elegant, succinct way ... – shevy Jan 01 '20 at 07:29
  • 4
    @shevy If you want to be terse you'll use `std::chrono_literals`, reducing the function argument to just `200ms`. – Ben Voigt Dec 04 '20 at 16:44
  • I place bulk of it under the headers: `#include using std::chrono::milliseconds; #include using std::this_thread::sleep_for;` to keep inline code more terse: `sleep_for(milliseconds(2000));` – chikega Apr 01 '23 at 21:47
20

For Windows:

#include "windows.h" 
Sleep(10);

For Unix:

#include <unistd.h>
usleep(10)
Bertram Gilfoyle
  • 9,899
  • 6
  • 42
  • 67
Dani
  • 14,639
  • 11
  • 62
  • 110
15

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().

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dicroce
  • 45,396
  • 28
  • 101
  • 140
11

Just use it...

Firstly include the unistd.h header file, #include<unistd.h>, and use this function for pausing your program execution for desired number of seconds:

sleep(x);

x can take any value in seconds.

If you want to pause the program for 5 seconds it is like this:

sleep(5);

It is correct and I use it frequently.

It is valid for C and C++.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Prasang Singhal
  • 121
  • 1
  • 2
  • 2
    @L.F. `usleep` takes microseconds, `sleep` (which this answer is written in terms of ) takes seconds -- so the answer is correct, albeit not portable – Human-Compiler Dec 13 '19 at 16:53
  • 1
    @Human-Compiler Sorry. Should’ve double checked before commenting. – L. F. Dec 13 '19 at 23:56
8

Prior to C++11, there was no portable way to do this.

A portable way is to use Boost or Ace library. There is ACE_OS::sleep(); in ACE.

L. F.
  • 19,445
  • 8
  • 48
  • 82
alexkr
  • 4,580
  • 1
  • 24
  • 21
  • 1
    ... and the (supposed) reason there is no portable way to do it in the standard is because the a clock's precision (smallest unit of time) is hardware-dependent or OS-dependent. No, I don't find it a convincing reason either, but there we are. – wilhelmtell Nov 01 '09 at 21:34
  • There is no such thing as thread defined by standard... and you want sleep. Sleep is a OS provided functionality. I can have environment which does not provide me such feature. – alexkr Nov 01 '09 at 21:41
  • @wilhelmtell: That is not the reason at all. Who is it making this supposition other than yourself? There is no standard for thread support (yest), and if there are no threads (or rather only one thread), there is no need for a thread sleep rather than a simple 'busy-wait', which can be implemented with /. The support must be provided by the thread library or OS. – Clifford Nov 01 '09 at 23:06
6

The simplest way I found for C++ 11 was this:

Your includes:

#include <chrono>
#include <thread>

Your code (this is an example for sleep 1000 millisecond):

std::chrono::duration<int, std::milli> timespan(1000);
std::this_thread::sleep_for(timespan);

The duration could be configured to any of the following:

std::chrono::nanoseconds   duration</*signed integer type of at least 64 bits*/, std::nano>
std::chrono::microseconds  duration</*signed integer type of at least 55 bits*/, std::micro>
std::chrono::milliseconds  duration</*signed integer type of at least 45 bits*/, std::milli>
std::chrono::seconds       duration</*signed integer type of at least 35 bits*/, std::ratio<1>>  
std::chrono::minutes       duration</*signed integer type of at least 29 bits*/, std::ratio<60>>
std::chrono::hours         duration</*signed integer type of at least 23 bits*/, std::ratio<3600>>
L. F.
  • 19,445
  • 8
  • 48
  • 82
Merav Kochavi
  • 4,223
  • 2
  • 32
  • 37
1

For a short solution use

#include <thread>

using namespace std;
using namespace std::this_thread;

void f() {
    sleep_for(200ms);
}
Sebastian
  • 1,834
  • 2
  • 10
  • 22
0

Recently I was learning about chrono library and thought of implementing a sleep function on my own. Here is the code,

#include <cmath>
#include <chrono>

template <typename rep = std::chrono::seconds::rep, 
          typename period = std::chrono::seconds::period>
void sleep(std::chrono::duration<rep, period> sec) {
    using sleep_duration = std::chrono::duration<long double, std::nano>;

    std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

    long double elapsed_time = 
    std::chrono::duration_cast<sleep_duration>(end - start).count();

    long double sleep_time = 
    std::chrono::duration_cast<sleep_duration>(sec).count();

    while (std::isgreater(sleep_time, elapsed_time)) {
        end = std::chrono::steady_clock::now();
        elapsed_time = std::chrono::duration_cast<sleep_duration>(end - start).count(); 
    }
}

We can use it with any std::chrono::duration type (By default it takes std::chrono::seconds as argument). For example,

#include <cmath>
#include <chrono>

template <typename rep = std::chrono::seconds::rep, 
          typename period = std::chrono::seconds::period>
void sleep(std::chrono::duration<rep, period> sec) {
    using sleep_duration = std::chrono::duration<long double, std::nano>;

    std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

    long double elapsed_time = 
    std::chrono::duration_cast<sleep_duration>(end - start).count();

    long double sleep_time = 
    std::chrono::duration_cast<sleep_duration>(sec).count();

    while (std::isgreater(sleep_time, elapsed_time)) {
        end = std::chrono::steady_clock::now();
        elapsed_time = std::chrono::duration_cast<sleep_duration>(end - start).count(); 
    }
}

using namespace std::chrono_literals;
int main (void) {
    std::chrono::steady_clock::time_point start1 = std::chrono::steady_clock::now();
    
    sleep(5s);  // sleep for 5 seconds
    
    std::chrono::steady_clock::time_point end1 = std::chrono::steady_clock::now();
    
    std::cout << std::setprecision(9) << std::fixed;
    std::cout << "Elapsed time was: " << std::chrono::duration_cast<std::chrono::seconds>(end1-start1).count() << "s\n";
    
    std::chrono::steady_clock::time_point start2 = std::chrono::steady_clock::now();

    sleep(500000ns);  // sleep for 500000 nano seconds/500 micro seconds
    // same as writing: sleep(500us)
    
    std::chrono::steady_clock::time_point end2 = std::chrono::steady_clock::now();
    
    std::cout << "Elapsed time was: " << std::chrono::duration_cast<std::chrono::microseconds>(end2-start2).count() << "us\n";
    return 0;
}

For more information, visit https://en.cppreference.com/w/cpp/header/chrono and see this cppcon talk of Howard Hinnant, https://www.youtube.com/watch?v=P32hvk8b13M. He has two more talks on chrono library. And you can always use the library function, std::this_thread::sleep_for

Note: Outputs may not be accurate. So, don't expect it to give exact timings.

0

I like the solution proposed by @Ben Voigt -- it does not rely on anything outside of C++, but he did not mention an important detail to make the code work. So I am putting the full code, please notice the line starting with using.

#include <thread>
#include <chrono>

...

using namespace std::chrono_literals;
std::this_thread::sleep_for(200ms);
Yuriy Look
  • 11
  • 3