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++?

- 12,657
- 15
- 62
- 94
-
9You should be aware that, in Windows anyway, `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. – John Dibling Nov 15 '10 at 13:09
-
5@John Dibling: I think he's using POSIX `sleep`, not win32 `Sleep` given "x seconds". – CB Bailey Nov 15 '10 at 13:14
-
1Although C and C++ have different name mangling, which can be a source of bugs and incompatibilities, in most cases it's fine to use C headers in C++. However, if you want to be absolutely sure that nothing goes wrong, `#include` the C header inside an `extern "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. – notadam Mar 17 '15 at 12:56
-
4@JohnDibling no, not 400ms. The worst precision you might ever have gotten was from Windows 9x, whose `GetTickCount` had 55ms resolution; later versions had 16ms resolution or less. One user [thought he was getting 16ms resolution from Sleep](https://social.msdn.microsoft.com/Forums/en-US/0430f043-443d-451a-bf6b-10de6bfeba29/sleep-function-is-not-accurate?forum=Vsexpressvc) but then reported that `Sleep` itself was fairly accurate, and the apparent imprecision was caused by using `GetTickCount` to measure the passage of time. – Qwertie Jan 10 '19 at 21:20
-
I had just fallen into this MS trap in Windows 10. Using the QueryPerformanceCounter a Sleep(1) returns after about 14 ms. – Günter May 17 '22 at 21:15
-
There's `usleep()` on POSIX compliant platforms.. – Jesper Juhl Apr 17 '23 at 11:52
19 Answers
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.

- 27,591
- 48
- 66
- 103

- 50,428
- 24
- 122
- 194
-
6Does std::this_thread::sleep_for define an interruption point? Like boost::this_thread_sleep does? – Martin Meeser Jul 18 '13 at 09:28
-
97This is the right way to do it. Period. Thread is cross platform as well as chrono. – Void Nov 19 '13 at 18:36
-
122@Void. A very good way certainly, but "the" and "period" are awfully strong words. – Mad Physicist Jan 04 '15 at 07:12
-
1this method is not the best because it has delay, as mentioned in [Note that multi-threading management may cause certain delay beyond this](http://www.cplusplus.com/reference/thread/this_thread/sleep_for/) – Valen Feb 17 '15 at 05:13
-
2
-
@HighCommander4 , probably not, or need to travel inside the os, or use a single core, single thread processor lol. – Valen Feb 17 '15 at 12:32
-
11Is it a busy sleep? I need to yield to another thread during sleep; can I use `sleep_for` for that? – Michael Oct 08 '15 at 18:31
-
25@Michael: It's not a busy sleep, it will yield to other threads. – HighCommander4 Oct 09 '15 at 02:32
-
@Void If possible, certainly! But if you can't use C++11, or if you're compiling without standard library support, you must do something else. – Kyle Strand Nov 11 '15 at 16:34
-
1I support @Valen in that way, that a much better name for the method would be std::this_thread::REQUEST_reactivation_after(...). But this is called sleep as long everyone can think of ... – Martin Meeser Feb 08 '16 at 13:11
-
1
-
3
-
1@Abhinav Gauniyal It means checking very frequently if it should start again, therefore using a lot of CPU doing nothing. As you probably guessed, this is usually undesirable, especially when you have other threads that have actual work to do. – Loomchild Feb 03 '17 at 09:35
-
Is there any rule or reason why one of us can't just edit the accepted answer to say what this answer says? This is the correct answer after all. – ahcox Aug 02 '17 at 16:34
-
1@MartinMeeser, no the standard did not choose to support the interruption point feature of Boost threads at all. – ahcox Aug 02 '17 at 16:36
-
Does it bother anyone else to have a statement with this_thread, just for a sleep function. It really throws me off to include
when there is no threading in my program – JeffCharter Sep 18 '17 at 22:29 -
2Are you sure the actual minimum time isn't 15-16 ms in some cases (even if e.g. 3 ms is specified)? Have you measured it (e.g. with the high-resolution timer)? – Peter Mortensen Oct 06 '17 at 17:40
-
@MadPhysicist you imply you disagree, saying '"the" and "period" are awfully strong words' yet neither you nor anyone else has proposed a reason not to use it. Don't just disagree because it's the web. You need a reason. – Qwertie Jan 10 '19 at 21:46
-
8@Qwertie. My reason is that "This is the right way to do it. Period" is an absolute statement implying A) that there is a "right" way that is the same for all cases, and B) that there is no other way that is equally "right", at least in some situations. At no point did I imply that I find the solution in the answer inadequate in any way: "A very good way certainly" was how I described it. My objection is to the use of absolutes. There are other possible good solutions, and to imply otherwise seems to unreasonable to me, hence the comment. – Mad Physicist Jan 10 '19 at 22:12
-
1From C++11 you can use even shorter form using numeric literals `std::this_thread::sleep_for(123ms);`. See my other post here. – Martin Flaska May 26 '21 at 11:34
-
regarding "the right way": Original question asked for C++. Since C++11, this is the definitive answer. Alternatives (like nanosleep, or usleep) are POSIX, and thus they are C solutions and portable to the degree that POSIX is. Both solutions have in common that they rely on the OS scheduler, and thus typically add granularity and a "at least" condition. For high precision, use a busy wait on a high resolution timer. – Ichthyo Dec 24 '21 at 19:46
-
How can you cancel this sleep - without implementing a busy-wait – Tobi Akinyemi Apr 17 '22 at 21:09
-
@TobiAkinyemi Presumably there is another thread involved to trigger the cancellation. In such cases, you would typically use a condition variable as described e.g. in [this answer](https://stackoverflow.com/a/29775639). If that does not answer your question, probably best to ask it in a new question rather than a comment. – HighCommander4 Apr 18 '22 at 01:06
-
@HighCommander4 Thanks. I was concerned with `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 – Tobi Akinyemi Apr 18 '22 at 13:34
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);

- 12,111
- 21
- 91
- 136

- 320,036
- 81
- 464
- 592
-
3Is it a busy sleep? I need to yield to another thread during sleep; can I use `usleep` for that? – Michael Oct 08 '15 at 18:30
-
16It's not a busy wait http://stackoverflow.com/a/8156644/1206499, and `nanosleep`may be a better choice since `usleep` is obsolete. – jswetzen Dec 03 '15 at 14:55
-
5Niet, please consider mentioning @HighCommander4's answer which is more portable if you have a C++11 compiler. – einpoklum Nov 14 '16 at 15:54
-
10
-
Apparently `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()`](https://stackoverflow.com/questions/10053788/implicit-declaration-of-function-usleep/55860234#55860234). – Gabriel Staples Nov 10 '21 at 03:56
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.
-
6Keep in mind that - in a multi-threaded environment -`boost::this_thread::sleep` adds an interruption point to your code. http://www.boost.org/doc/libs/1_49_0/doc/html/thread/thread_management.html – Martin Meeser Jul 18 '13 at 09:25
-
7
-
20
-
Yes, but couldn't the actual time resolution be 15-16 ms (even if the unit in the call is 1 ms) and thus the minimum time be 15-16 ms? – Peter Mortensen Oct 06 '17 at 17:38
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.

- 755,051
- 104
- 632
- 656
-
6Note that while `usleep()` is declared in `
`, confusingly, `nanosleep()` is declared in ` – gbmhunter May 07 '14 at 05:14`/` `.
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;
}

- 5,141
- 5
- 38
- 59

- 373
- 3
- 5
-
34One of the problems with that code is that it is a busy loop, it will continue using the 100% of a single processor core. The sleep function is implemented around an OS call that will put to sleep the current thread and do something else, and only will wake up the thread when the specified time expires. – Ismael May 20 '14 at 22:53
-
You're right - it will consume 100% of a one CPU core. So here is rewritten code using system sleep functions - and it's still cross-platform: – Bart Grzybicki May 23 '14 at 22:25
-
@BartGrzybicki i know this is an old answer and all, but in Visual Studio 2017 on a windows machine, `#ifdef WIN32` doesn't evaluate as true by-default. – kayleeFrye_onDeck Jun 20 '18 at 03:02
-
2
-
1@Contango I knew that! But not when I wrote that... lol. Thanks for the follow-up! – kayleeFrye_onDeck Aug 22 '19 at 21:01
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);

- 673
- 7
- 10
-
3
-
3In short, it is implemented as user-defined literal, similarly as you define other operators: long double operator "" ms(long double) In my opinion is is better readable than `chrono::milliseconds(1000)`. See [User-defined literals][1] for more info. [1]: https://en.cppreference.com/w/cpp/language/user_literal – Martin Flaska May 26 '21 at 11:22
#include <windows.h>
Syntax:
Sleep ( __in DWORD dwMilliseconds );
Usage:
Sleep (1000); //Sleeps for 1000 ms or 1 sec

- 928
- 1
- 13
- 22

- 2,887
- 2
- 30
- 55
nanosleep
is a better choice than usleep
- it is more resilient against interrupts.

- 25,185
- 9
- 78
- 101
-
7I was familiar with `usleep`, but not `nanosleep`. You should provide an example of using it on Linux. – jww Aug 14 '16 at 03:10
If using MS Visual C++ 10.0, you can do this with standard library facilities:
Concurrency::wait(milliseconds);
you will need:
#include <concrt.h>
-
14Don't use the word "standard" when you don't actually mean it. `
` is *not* a Standard Library header - it may be a platform library; in which case you should state the prerequisites clearly. – Toby Speight Jul 14 '17 at 09:09 -
Not only that, but we'd expect a [tag:linux] question to be using one of the popular compilers. – Toby Speight Jan 15 '21 at 12:52
-
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.

- 30,738
- 21
- 105
- 131

- 131,725
- 17
- 180
- 271
-
Can't seem to compile in VS2017 on a Windows machine: `error LNK2019: unresolved external symbol _select@20 referenced in function "void __cdecl sleep(unsigned long)" (?sleep@@YAXK@Z)` – kayleeFrye_onDeck Jun 20 '18 at 03:07
-
@kayleeFrye_onDeck It does compile. Just doesn't link. Lookup you Windows docs. – Maxim Egorushkin Jun 20 '18 at 09:10
-
-
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

- 30,738
- 21
- 105
- 131

- 224
- 2
- 9
-
3What do you mean it has no limit? It surely has limit which is 0xFFFFFFFE. Waiting for 0xFFFFFFFF will just not time out (which means it will wait till program ends). – Izzy Jan 16 '15 at 09:31
-
I didn't mean it like that Izzy, sorry for our misunderstanding. I meant that you can enter any positive number of milliseconds. So it will wait that many milliseconds to close the program. If you do not understand please say so, I shall explain to you more. – Phi Jan 18 '15 at 16:54
-
Yes, but what it the actual time resolution? Couldn't it be 15-16 ms in some cases? E.g., if you use Sleep(3) will it actually sleep for 3 ms or will it instead be 15-16 ms? – Peter Mortensen Oct 06 '17 at 17:46
-
Select call is a way of having more precision (sleep time can be specified in nanoseconds).

- 31
- 2
-
1While this might be a valuable hint to solve the problem, a good answer also demonstrates the solution. Please [edit] to provide example code to show what you mean. Alternatively, consider writing this as a comment instead. – Toby Speight Jul 14 '17 at 09:10
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));

- 30,738
- 21
- 105
- 131

- 2,383
- 1
- 29
- 54
-
2What will actually happen if you try to sleep for 3 milliseconds? Will it be 15-16 milliseconds instead? Have you measured it? – Peter Mortensen Oct 06 '17 at 17:54
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
}

- 4,473
- 1
- 44
- 33
-
Prefer `nanosleep()` to `usleep()`: the latter is deprecated and has been deleted from the most recent POSIX standard. – Toby Speight Jul 14 '17 at 09:13
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

- 741
- 8
- 19
-
3You probably meant `usleep((X) * 1000)` - which is one reason why functions are so much better than macros! – Toby Speight Jan 15 '21 at 12:45
-
@TobySpeight yes, if it will be an expression where you sum up two number msleep(1 + 2), then the macro substitution will be usleep(1 + 2 * 1000) will be 2001 instead of 3000 Making usleep ((X) * 1000) , guarantees that (1+2) will be evaluated first. Just for those who are not aware, though it is basics of macros. Don't use them especially if you are not aware of how they work in principle. – Nusrat Nuriyev Jun 12 '23 at 15:07
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 );
}

- 51
- 1
- 3
I use this:
#include <thread>
#define sleepms(val) std::this_thread::sleep_for(val##ms)
example:
sleepms(200);

- 441
- 3
- 10
for C use /// in gcc.
#include <windows.h>
then use Sleep(); /// Sleep() with capital S. not sleep() with s .
//Sleep(1000) is 1 sec /// maybe.
clang supports sleep(), sleep(1) is for 1 sec time delay/wait.

- 35
- 6