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++?
Join Stack Overflow to learn, share knowledge, and build your career.
|
Note that there is no standard C API for milliseconds, so (on Unix) you will have to settle for
|
|||||||||||||||||
|
|
Use Boost asynchronous input/output threads, sleep for x milliseconds;
|
|||||||||
|
|
On platforms with the
However, there are better alternatives available nowadays. |
||||
|
|
|
The way to sleep your program in C++ is the For example:
The time it sleeps is measured in milliseconds and has no limit.
|
|||||||||||||
|
|
Why don't use time.h library? Runs on Windows and POSIX systems:
Corrected code - now CPU stays in IDLE state [2014.05.24]:
|
|||||||||
|
Syntax:
Usage:
|
|||||||||||||||||
|
|
In C++11, you can do this with standard library facilities:
Clear and readable, no more need to guess at what units the |
|||||||||||||||||||||
|
|
As a Win32 replacement for POSIX systems:
|
|||||
|
|
If using MS Visual C++ 10.0, you can do this with standard library facilities:
you will need:
|
|||||
|
|
|
|||||||||||||
|
|
Select call is a way of having more precision (sleep time can be specified in nanoseconds). |
|||||
|
|
Depending on your platform you may have |
|||||
|
|
|
|||||
|
|
To stay portable you could use Boost::Thread for sleeping:
This answer is a duplicate and has been posted in this question before. Perhaps you could find some usable answers there too. |
|||||
|
protected by Community♦ Aug 11 '15 at 17:58
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
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:09sleep, not win32Sleepgiven "x seconds". – Charles Bailey Nov 15 '10 at 13:14#includethe C header inside anextern "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. – adam10603 Mar 17 '15 at 12:56