Sleep Function in C
Problem:
In C , how can you pause a program for a specified duration in milliseconds, similar to Sleep(time); in other languages?
Header and Function Signature:
To facilitate sleeping in C , include the
<code class="cpp">std::this_thread::sleep_for(std::chrono::milliseconds timespan);</code>
Solution:
To pause the program for a specific amount of time, use the following syntax:
<code class="cpp">std::chrono::milliseconds timespan(111605); // or any desired time std::this_thread::sleep_for(timespan);</code>
Historical Sleep Functions:
Prior to C 11, C lacked thread and sleep capabilities. The following platform-dependent solution was utilized:
<code class="cpp">#ifdef _WIN32 #include <windows.h> void sleep(unsigned milliseconds) { Sleep(milliseconds); } #else #include <unistd.h> void sleep(unsigned milliseconds) { usleep(milliseconds * 1000); // takes microseconds } #endif</code>
Alternatively, a simpler pre-C 11 option was to use boost::this_thread::sleep.
The above is the detailed content of How to Pause Execution in C for a Specified Duration?. For more information, please follow other related articles on the PHP Chinese website!