Sleep for milliseconds

2019-01-01 05:57发布

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

标签: c++ linux sleep
14条回答
春风洒进眼中
2楼-- · 2019-01-01 06:45

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

查看更多
爱死公子算了
3楼-- · 2019-01-01 06:46

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);
查看更多
伤终究还是伤i
4楼-- · 2019-01-01 06:46

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.

查看更多
不再属于我。
5楼-- · 2019-01-01 06:47

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));
查看更多
零度萤火
6楼-- · 2019-01-01 06:50

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.

查看更多
时光乱了年华
7楼-- · 2019-01-01 06:53

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.

查看更多
登录 后发表回答