How to Sleep for Milliseconds in C++?
In programming, sleeping for milliseconds means pausing the execution of the current thread for a specified number of milliseconds, it is often used in cases like creating delays, controlling the execution speed of a program, or simulating a time-consuming operation. In this article, we will learn how to sleep a program for milliseconds in C++.
Sleep for Milliseconds in C++
To sleep for milliseconds in C++, we can use the std::this_thread::sleep_for function. This function is like a C++ version of the sleep function from the <thread> library that takes a duration as an argument and pauses the execution of the current thread for that duration. We can specify the duration in milliseconds using the std::chrono::milliseconds function from the <chrono> library.
Syntax to Use std::this_thread::sleep_for Function
this_thread::sleep_for(chrono::milliseconds(duration));
Here, duration is the time in milliseconds for which you want to sleep.
C++ Program to Sleep for Milliseconds
The below program demonstrates how to make a program sleep for milliseconds in C++.
// C++ program to sleep for milliseconds
#include <chrono>
#include <iostream>
#include <thread>
using namespace std;
int main()
{
// Print message indicating the start of program
// execution.
cout << "Execution Started.." << endl;
// using for loop to print the interations
for (int i = 0; i < 6; i++) {
// Print the current loop counter value.
cout << i << endl;
// Check if the loop counter value is 3.
if (i == 3) {
// Print message indicating the program is about
// to sleep.
cout << "Sleeping for 5000 milliseconds..."
<< endl;
// Pause the program execution for 5000
// milliseconds.
this_thread::sleep_for(
chrono::milliseconds(5000));
// Print message indicating the program has
// resumed after sleeping.
cout << "Program Resumed" << endl;
}
}
return 0;
}
Output
Execution Started..
0
1
2
3
Sleeping for 5000 milliseconds....
Program Resumed
4
5
Time Complexity: O(1)
Auxiliary Space: O(1)
Note: The std::this_thread::sleep_for and std::chrono::milliseconds functions are defined in the C++11 standard. So, these functions may not run with older compilers.