866

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

8
  • 10
    You 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. Commented Nov 15, 2010 at 13:09
  • 5
    @John Dibling: I think he's using POSIX sleep, not win32 Sleep given "x seconds".
    – CB Bailey
    Commented Nov 15, 2010 at 13:14
  • 1
    Although 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
    Commented Mar 17, 2015 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 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
    Commented Jan 10, 2019 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
    Commented May 17, 2022 at 21:15

19 Answers 19

1723

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.

23
  • 6
    Does std::this_thread::sleep_for define an interruption point? Like boost::this_thread_sleep does? Commented Jul 18, 2013 at 9:28
  • 100
    This is the right way to do it. Period. Thread is cross platform as well as chrono.
    – Void
    Commented Nov 19, 2013 at 18:36
  • 129
    @Void. A very good way certainly, but "the" and "period" are awfully strong words. Commented Jan 4, 2015 at 7:12
  • 11
    Is it a busy sleep? I need to yield to another thread during sleep; can I use sleep_for for that?
    – Michael
    Commented Oct 8, 2015 at 18:31
  • 26
    @Michael: It's not a busy sleep, it will yield to other threads. Commented Oct 9, 2015 at 2:32
527

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);
5
86

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.

1
43

In Unix you can use usleep.

In Windows there is Sleep.

3
  • 7
    and the Windows call is in milliseconds.
    – shindigo
    Commented Sep 13, 2013 at 14:06
  • 20
    You have to include <unistd.h> or <Windows.h> respectively.
    – gbmhunter
    Commented May 7, 2014 at 5:13
  • 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? Commented Oct 6, 2017 at 17:38
42

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);
2
  • 3
    How is this implemented? 123ms looks weird.
    – vy32
    Commented May 24, 2021 at 0:56
  • 6
    In 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]: en.cppreference.com/w/cpp/language/user_literal Commented May 26, 2021 at 11:22
33

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.

1
  • 6
    Note that while usleep() is declared in <unistd.h>, confusingly, nanosleep() is declared in <time.h>/<ctime>.
    – gbmhunter
    Commented May 7, 2014 at 5:14
29

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;
}
3
  • @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. Commented Jun 20, 2018 at 3:02
  • 2
    @kayleeFrye_onDeck Code is wrong. It should be #ifdef _WIN32.
    – Contango
    Commented Aug 22, 2019 at 20:59
  • 1
    @Contango I knew that! But not when I wrote that... lol. Thanks for the follow-up! Commented Aug 22, 2019 at 21:01
18

nanosleep is a better choice than usleep - it is more resilient against interrupts.

1
  • 8
    I was familiar with usleep, but not nanosleep. You should provide an example of using it on Linux.
    – jww
    Commented Aug 14, 2016 at 3:10
18
#include <windows.h>

Syntax:

Sleep (  __in DWORD dwMilliseconds   );

Usage:

Sleep (1000); //Sleeps for 1000 ms or 1 sec
4
  • 4
    What do you need to include for this? Commented Jun 25, 2014 at 4:21
  • #include <WinBase.h>
    – foobar
    Commented Jun 25, 2014 at 5:40
  • 10
    No, you need to #include <windows.h> Commented Jun 26, 2014 at 2:39
  • 10
    The question strongly implies that a POSIX solution is required. Commented Jul 14, 2017 at 9:10
6

If using MS Visual C++ 10.0, you can do this with standard library facilities:

Concurrency::wait(milliseconds);

you will need:

#include <concrt.h>
4
  • 16
    Don't use the word "standard" when you don't actually mean it. <concrt.h> is not a Standard Library header - it may be a platform library; in which case you should state the prerequisites clearly. Commented Jul 14, 2017 at 9:09
  • Not only that, but we'd expect a linux question to be using one of the popular compilers. Commented Jan 15, 2021 at 12:52
  • Cannot be used with CLR (compiler option /clr).
    – Günter
    Commented May 17, 2022 at 21:30
  • This was posted in 2015. Is there any reason you'd ever use this instead of std::chrono? Perhaps a codebase that wasn't ready to move to C++11 yet? I assume it's pretty much obsolete in 2023. Commented Dec 21, 2023 at 3:36
5

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.

4
  • 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) Commented Jun 20, 2018 at 3:07
  • @kayleeFrye_onDeck It does compile. Just doesn't link. Lookup you Windows docs. Commented Jun 20, 2018 at 9:10
  • what header do you use for timeval ?? Commented Jun 9, 2020 at 1:48
  • @TotteKarlsson <sys/time.h>. Commented Jun 9, 2020 at 8:52
3

Select call is a way of having more precision (sleep time can be specified in nanoseconds).

1
  • 2
    While 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. Commented Jul 14, 2017 at 9:10
3

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
5
  • 3
    What 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
    Commented Jan 16, 2015 at 9: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
    Commented Jan 18, 2015 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? Commented Oct 6, 2017 at 17:46
  • I don't think "windows.h" is a standard POSIX or Linux header... Commented Jan 15, 2021 at 12:50
  • "The way to sleep your program in C++ is the Sleep(int) method" - That was a pretty odd thing to write in 2014, 3 years after C++11 was released.
    – Ted Lyngmo
    Commented Jan 18 at 20:43
2

C++14: sleep for 10 seconds:

#include <thread>
#include <chrono>

using namespace std::chrono_literals;
std::this_thread::sleep_for(10s);

for 10 milliseconds use 10ms

1

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));
1
  • 2
    What will actually happen if you try to sleep for 3 milliseconds? Will it be 15-16 milliseconds instead? Have you measured it? Commented Oct 6, 2017 at 17:54
1

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 );
}

0

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
}
1
  • Prefer nanosleep() to usleep(): the latter is deprecated and has been deleted from the most recent POSIX standard. Commented Jul 14, 2017 at 9:13
0

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
2
  • 3
    You probably meant usleep((X) * 1000) - which is one reason why functions are so much better than macros! Commented Jan 15, 2021 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. Commented Jun 12, 2023 at 15:07
0

I use this:

#include <thread>
#define sleepms(val) std::this_thread::sleep_for(val##ms)

example:

sleepms(200);

Not the answer you're looking for? Browse other questions tagged or ask your own question.