CodingKnight's blog

By CodingKnight, 3 years ago, In English

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.

class Timer

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.

Example

The following is the stdout printed results of the example program.

Output

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.

  • Vote: I like it
  • +72
  • Vote: I do not like it

»
3 years ago, # |
Rev. 2   Vote: I like it -15 Vote: I do not like it

Great!! gonna help with the TLEs will it?

  • »
    »
    3 years ago, # ^ |
    Rev. 8   Vote: I like it +3 Vote: I do not like 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.

  • »
    »
    3 years ago, # ^ |
      Vote: I like it +40 Vote: I do not like it

    Yes, it will, just change elapsed_time like so:

    inline value_t elapsed_time() const {
        	return value_t(duration_cast<units>(clock::now()-t0).count()/10); }
    

    and your code will become dramatically faster; try it yourself if you don't believe me.