We will write a short program that just puts the main thread to sleep for certain amounts of time:
- Let's first include all the needed headers and declare that we'll use the std and chrono_literals namespaces. The chrono_literals namespace contains handy abbreviations for creating time-span values:
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
using namespace chrono_literals;
- Let's immediately put the main thread to sleep for 5 seconds and 300 milliseconds. Thanks to chrono_literals, we can express this in a very readable format:
int main()
{
cout << "Going to sleep for 5 seconds"
" and 300 milli seconds.n";
this_thread::sleep_for(5s + 300ms);
- The last sleep statement was relative. We can also express absolute sleep requests. Let's sleep until the point in time, which is now plus 3 seconds:
cout << "Going to sleep for another 3 seconds.n";
this_thread::sleep_until(
chrono::high_resolution_clock::now() + 3s);
- Before quitting the program, let's print something else to signal the end of the second sleep period:
cout << "That's it.n";
}
- Compiling and running the program yields the following results. Linux, Mac, and other UNIX-like operating systems provide the time command, which accepts another command in order to execute it and stop the time it takes. Running our program with time shows that it ran 8.32 seconds, which is roughly the 5.3 and 3 seconds we let our program sleep. When running the program, it is possible to count the time between the arrival of the printed lines on the terminal:
$ time ./sleep
Going to sleep for 5 seconds and 300 milli seconds.
Going to sleep for another 3 seconds.
That's it.
real 0m8.320s
user 0m0.005s
sys 0m0.003s