Fixed time step
This pattern is licensed under the CC0 Public Domain Dedication.
Block the execution of a thread until a fixed point in time.
For the purposes of demonstrating this pattern, we use
std::chrono::steady_clock (line 10),
although any other clock will suffice.
On line 11, we create a
clock::time_point representing the point in
time five seconds from now. To do so, we use
clock::now() to get
the current time point and add the duration of
5s to it. Here we
have used one of C++14’s duration literal
to representing a duration with the seconds suffix,
using directive on line 4 is required in order to use these suffixes.
For C++11, the duration can be constructed manually.
After performing some complex work on line 13, we then call
std::this_thread::sleep_until on line 15,
passing it the time point we computed earlier. This blocks the
current thread until we have reached that time point, ensuring that
execution continues exactly five seconds after the starting time,
regardless of how much time the complex work took (unless it took
more than five seconds).
This technique is most commonly used in a loop to ensure that the loop iterates with a fixed time step. Alternatively, if you want to sleep for a fixed amount of time, see the sleep sample.
27 August 2018