[c++] Sleep for milliseconds

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

This question is related to c++ linux sleep

The answer is


Why don't use time.h library? Runs on Windows and POSIX systems:

#include <iostream>
#include <time.h>

using namespace std;

void sleepcp(int milliseconds);

void sleepcp(int milliseconds) // Cross-platform sleep function
{
    clock_t time_end;
    time_end = clock() + milliseconds * CLOCKS_PER_SEC/1000;
    while (clock() < time_end)
    {
    }
}
int main()
{
    cout << "Hi! At the count to 3, I'll die! :)" << endl;
    sleepcp(3000);
    cout << "urrrrggghhhh!" << endl;
}

Corrected code - now CPU stays in IDLE state [2014.05.24]:

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

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

Concurrency::wait(milliseconds);

you will need:

#include <concrt.h>

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


#include <chrono>
#include <thread>

std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // sleep for 1 second

Remember to import the two headers.


In Unix you can use usleep.

In Windows there is Sleep.


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

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.


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.


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.


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

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.


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
}

#include <windows.h>

Syntax:

Sleep (  __in DWORD dwMilliseconds   );

Usage:

Sleep (1000); //Sleeps for 1000 ms or 1 sec

From C++14 using std and also its numeric literals:

#include <chrono>
#include <thread>

using namespace std::chrono;

std::this_thread::sleep_for(123ms);

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


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

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.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to sleep

How to make the script wait/sleep in a simple way in unity How do I make a delay in Java? How to create a sleep/delay in nodejs that is Blocking? Javascript sleep/delay/wait function How can I perform a short delay in C# without using sleep? How to add a "sleep" or "wait" to my Lua Script? How to create javascript delay function JavaScript sleep/wait before continuing powershell mouse move does not prevent idle mode What is the proper #include for the function 'sleep()'?