Pausing Program Execution in C with the Sleep Function
Many programming languages offer a sleep function to pause program execution for a specified duration. In C , the corresponding function is slightly different.
Question:
How can we pause a C program for a certain number of milliseconds using a sleep function?
Answer:
In C , the standard library provides the std::this_thread::sleep_for function to achieve this. Here's how to use it:
Add the following headers:
<code class="cpp">#include <chrono> #include <thread></code>
Create a std::chrono::milliseconds object representing the desired duration:
<code class="cpp">std::chrono::milliseconds timespan(111605); // or any desired value</code>
Pause the program for the specified duration using std::this_thread::sleep_for:
<code class="cpp">std::this_thread::sleep_for(timespan);</code>
Pre-C 11 Sleep Functions:
Before C 11, C didn't have a standard sleep function. Here are some platform-dependent options:
However, a better pre-C 11 method is to use the Boost library: boost::this_thread::sleep.
The above is the detailed content of How to Pause Program Execution in C Using a Sleep Function. For more information, please follow other related articles on the PHP Chinese website!