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 sign
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
.
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++.
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()
.
You'll need at least C++11.
#include <thread>
#include <chrono>
...
std::this_thread::sleep_for(std::chrono::milliseconds(200));
For Windows:
#include "windows.h"
Sleep(10);
For Unix:
#include <unistd.h>
usleep(10)
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>>