Hello Codeforces,
This is an update to an old blog I wrote 15 months ago about measuring elapsed time between two events in C++ programs on real-time scale such as milliseconds using the std::chrono library classes and functions.
The following is the class declaration and implementation.
The template has two parameters: clock
and units
corresponding to the used std::chrono clock and time units of the timer interval, respectively. The value passed to clock
should be high_resolution_clock
, system_clock
, or steady_clock
. The default value for units
is milliseconds
. Other possible values for units
include nanoseconds
, microseconds
, etc. check chrono::duration for more details.
The class has three public member functions:
Timer(const units interval);
units elapsed_time() const;
bool expired();
The first public member function Timer(const units interval)
is the class constructor used to create a timer object. The second function elapsed_time()
returns the elapsed time since the creation of the object. The third function expired()
returns false
if such elapsed time has not reached interval
yet; otherwise, the function returns true
.
The following is an example program to test the functionality of the class by creating a timer object with 1.5 sec interval.
The following is the stdout
printed results of the example program.
Your constructive comments and feedback are welcome.
Update: The third parameter value_t
was removed from the template to make the class declaration more compact.
Great!! gonna help with the TLEs will it?
It does simplify checking that the elapsed time at run-time has not reached a time-point very close to the time-limit. This is useful in approximate problems when you would like to run a particular optimization iteration for as long as the time-limit of the problem permits without fixing the number of iterations at compile-time, and avoid getting TLE Verdict.
Yes, it will, just change elapsed_time like so:
and your code will become dramatically faster; try it yourself if you don't believe me.