This post will discuss how to add a time delay to a C++ program. In other words, implement sleep in C++.

1. Using sleep_for() function

Since C++11, we can use std::this_thread::sleep_for function to block the execution of the current thread for the specified duration. The duration can be of type std::chrono::nanoseconds, std::chrono::microseconds, std::chrono::milliseconds, std::chrono::seconds, std::chrono::minutes, or std::chrono::hours.

 
The std::this_thread::sleep_for function and above durations are defined in the namespace std::chrono. Note that C++20 introduced a few more durations – std::chrono::days, std::chrono::weeks, std::chrono::months, and std::chrono::years to the standard.

Download  Run Code

 
With C++14, we can further simplify the code using the literal suffixes (ns, us, ms, s, h, etc.) for the std::chrono durations. This would need the std::chrono_literals namespace.

Download  Run Code

2. Using sleep_until() function

C++ also provides the std::this_thread::sleep_until function, which blocks the execution of the current thread until the specified duration has been reached. It can be used as follows to add a time delay:

Download  Run Code

 
Starting with C++14, consider using the literal suffixes (ns, us, ms, s, h, etc.) from the std::chrono_literals namespace.

Download  Run Code

3. Using Sleep() function

In a Windows environment, we can use the sleep() function to suspend the execution of the current thread until the specified number of milliseconds elapses. This is available in the <windows.h> header.

Download Code

 
Alternatively, we can use the sleep() function in Unix environment which sleeps for the specified number of seconds. This requires <unistd.h> header.

Download  Run Code

 
To suspend execution of a current thread for microsecond intervals, use the usleep() function instead. The nanosleep() is also available, which takes nanosecond interval.

Download  Run Code

4. Using Boost

Finally, we can use the date-time functions offered by the boost library. The following solution uses boost::this_thread::sleep from header <boost/thread/thread.hpp> to sleep for the specified duration:

Download Code

That’s all about adding a time delay to a C++ program.