![]() |
VOOZH | about |
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++.
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.
this_thread::sleep_for(chrono::milliseconds(duration));Here, duration is the time in milliseconds for which you want to sleep.
The below program demonstrates how to make a program sleep for milliseconds in C++.
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.