Advertisement
Advertisement


Sleep for milliseconds


Question

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

2015/02/04
1
644
2/4/2015 10:30:06 AM

Accepted Answer

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);
2014/05/02
462
5/2/2014 8:23:02 PM


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.

2017/05/23

In Unix you can use usleep.

In Windows there is Sleep.

2014/08/19

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.

2010/11/15

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;
}
2019/08/23

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

2010/11/15

Source: https://stackoverflow.com/questions/4184468
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]