I know the POSIX sleep(x)
function makes the program sleep for x seconds. Is there a function to make the program sleep for x milliseconds in C++?
Note that there is no standard C API for milliseconds, so (on Unix) you will have to settle for usleep
, which accepts microseconds:
#include <unistd.h>
unsigned int microseconds;
...
usleep(microseconds);
usleep
for that? –
Jori nanosleep
may be a better choice since usleep
is obsolete. –
Shut usleep()
is deprecated, so I wrote an example here to show how to write your own sleep_us()
(or usleep()
) function as a wrapper around nanosleep()
. –
Mikey In C++11, you can do this with standard library facilities:
#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::milliseconds(x));
Clear and readable, no more need to guess at what units the sleep()
function takes.
sleep_for
for that? –
Jori busy_sleep
? –
Bucella std::this_thread::sleep_for(123ms);
. See my other post here. –
Medallion condition_variable
busy waiting (which I found was true when doing some research some months ago). However, It's much easier to use the std apis than having to implement my own OS-specific impls, so until I reach the performance issues I was concerned about, I'll go with that solution –
Engaged Note that there is no standard C API for milliseconds, so (on Unix) you will have to settle for usleep
, which accepts microseconds:
#include <unistd.h>
unsigned int microseconds;
...
usleep(microseconds);
usleep
for that? –
Jori nanosleep
may be a better choice since usleep
is obsolete. –
Shut usleep()
is deprecated, so I wrote an example here to show how to write your own sleep_us()
(or usleep()
) function as a wrapper around nanosleep()
. –
Mikey To stay portable you could use Boost::Thread for sleeping:
#include <boost/thread/thread.hpp>
int main()
{
//waits 2 seconds
boost::this_thread::sleep( boost::posix_time::seconds(1) );
boost::this_thread::sleep( boost::posix_time::milliseconds(1000) );
return 0;
}
This answer is a duplicate and has been posted in this question before. Perhaps you could find some usable answers there too.
boost::this_thread::sleep
adds an interruption point to your code. boost.org/doc/libs/1_49_0/doc/html/thread/… –
Odelsting From C++14 using std and also its numeric literals:
#include <chrono>
#include <thread>
using namespace std::chrono_literals;
std::this_thread::sleep_for(123ms);
123ms
looks weird. –
Inspiratory chrono::milliseconds(1000)
. See [User-defined literals][1] for more info. [1]: en.cppreference.com/w/cpp/language/user_literal –
Medallion Depending on your platform you may have usleep
or nanosleep
available. usleep
is deprecated and has been deleted from the most recent POSIX standard; nanosleep
is preferred.
usleep()
is declared in <unistd.h>
, confusingly, nanosleep()
is declared in <time.h>
/<ctime>
. –
Greyhen Why don't use time.h
library? Runs on Windows and POSIX systems (don't use this code in production!):
CPU stays in IDLE state:
#include <iostream>
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif // _WIN32
using namespace std;
void sleepcp(int milliseconds);
void sleepcp(int milliseconds) // Cross-platform sleep function
{
#ifdef _WIN32
Sleep(milliseconds);
#else
usleep(milliseconds * 1000);
#endif // _WIN32
}
int main()
{
cout << "Hi! At the count to 3, I'll die! :)" << endl;
sleepcp(3000);
cout << "urrrrggghhhh!" << endl;
}
#ifdef WIN32
doesn't evaluate as true by-default. –
Censorship #ifdef _WIN32
. –
Boccie nanosleep
is a better choice than usleep
- it is more resilient against interrupts.
usleep
, but not nanosleep
. You should provide an example of using it on Linux. –
Citrin #include <windows.h>
Syntax:
Sleep ( __in DWORD dwMilliseconds );
Usage:
Sleep (1000); //Sleeps for 1000 ms or 1 sec
#include <WinBase.h>
–
Condone #include <windows.h>
–
Alexandretta If using MS Visual C++ 10.0, you can do this with standard library facilities:
Concurrency::wait(milliseconds);
you will need:
#include <concrt.h>
<concrt.h>
is not a Standard Library header - it may be a platform library; in which case you should state the prerequisites clearly. –
Autry std::chrono
? Perhaps a codebase that wasn't ready to move to C++11 yet? I assume it's pretty much obsolete in 2023. –
Encephalomyelitis On platforms with the select
function (POSIX, Linux, and Windows) you could do:
void sleep(unsigned long msec) {
timeval delay = {msec / 1000, msec % 1000 * 1000};
int rc = ::select(0, NULL, NULL, NULL, &delay);
if(-1 == rc) {
// Handle signals by continuing to sleep or return immediately.
}
}
However, there are better alternatives available nowadays.
error LNK2019: unresolved external symbol _select@20 referenced in function "void __cdecl sleep(unsigned long)" (?sleep@@YAXK@Z)
–
Censorship <sys/time.h>
. –
Unworthy Select call is a way of having more precision (sleep time can be specified in nanoseconds).
The way to sleep your program in C++ is the Sleep(int)
method. The header file for it is #include "windows.h."
For example:
#include "stdafx.h"
#include "windows.h"
#include "iostream"
using namespace std;
int main()
{
int x = 6000;
Sleep(x);
cout << "6 seconds have passed" << endl;
return 0;
}
The time it sleeps is measured in milliseconds and has no limit.
Second = 1000 milliseconds
Minute = 60000 milliseconds
Hour = 3600000 milliseconds
Sleep(int)
method" - That was a pretty odd thing to write in 2014, 3 years after C++11 was released. –
Astraphobia Use Boost asynchronous input/output threads, sleep for x milliseconds;
#include <boost/thread.hpp>
#include <boost/asio.hpp>
boost::thread::sleep(boost::get_system_time() + boost::posix_time::millisec(1000));
Elegant solution from the one answer, bit modified.. One can easilly add select() usage if there's no better functionality available. Just make function that uses select() etc. ..
Code:
#include <iostream>
/*
Prepare defines for millisecond sleep function that is cross-platform
*/
#ifdef _WIN32
# include <Windows.h>
# define sleep_function_name Sleep
# define sleep_time_multiplier_for_ms 1
#else
# include <unistd.h>
# define sleep_function_name usleep
# define sleep_time_multiplier_for_ms 1000
#endif
/* Cross platform millisecond sleep */
void cross_platform_sleep_ms(unsigned long int time_to_sleep_in_ms)
{
sleep_function_name ( sleep_time_multiplier_for_ms * time_to_sleep_in_ms );
}
As a Win32 replacement for POSIX systems:
void Sleep(unsigned int milliseconds) {
usleep(milliseconds * 1000);
}
while (1) {
printf(".");
Sleep((unsigned int)(1000.0f/20.0f)); // 20 fps
}
nanosleep()
to usleep()
: the latter is deprecated and has been deleted from the most recent POSIX standard. –
Autry The question is old, but I managed to figure out a simple way to have this in my app. You can create a C/C++ macro as shown below use it:
#ifndef MACROS_H
#define MACROS_H
#include <unistd.h>
#define msleep(X) usleep(X * 1000)
#endif // MACROS_H
usleep((X) * 1000)
- which is one reason why functions are so much better than macros! –
Autry I use this:
#include <thread>
#define sleepms(val) std::this_thread::sleep_for(val##ms)
example:
sleepms(200);
sleep for 10 seconds:
#include <thread>
#include <chrono>
using namespace std::chrono_literals;
std::this_thread::sleep_for(10s);
for 10 milliseconds use 10ms
© 2022 - 2024 — McMap. All rights reserved.
Sleep()
has millisecond precision, but it's accuracy can be orders of magnitude higher. You may think your sleeping for 4 milliseconds, but actually sleep for 400. – Economistsleep
, not win32Sleep
given "x seconds". – Selia#include
the C header inside anextern "C" {}
block. Also, if you have C and C++ source files in the same project, it's highly recommended that you do this in order to avoid any problems, especially if you include the same headers in both kinds of source files (in which case this is necessary). If you have a purely C++ project, it might just work with no problem at all. – AdolphusGetTickCount
had 55ms resolution; later versions had 16ms resolution or less. One user thought he was getting 16ms resolution from Sleep but then reported thatSleep
itself was fairly accurate, and the apparent imprecision was caused by usingGetTickCount
to measure the passage of time. – Glorygloryofthesnowusleep()
on POSIX compliant platforms.. – Bataanusleep
, the time isn't even a lower bound: a signal can wake the thread earlier. – Encephalomyelitis