Блог пользователя CodingKnight

Автор CodingKnight, 3 года назад, По-английски

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.

  • Проголосовать: нравится
  • +72
  • Проголосовать: не нравится

»
3 года назад, # |
Rev. 2   Проголосовать: нравится -15 Проголосовать: не нравится

Great!! gonna help with the TLEs will it?

  • »
    »
    3 года назад, # ^ |
    Rev. 8   Проголосовать: нравится +3 Проголосовать: не нравится

    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 года назад, # ^ |
      Проголосовать: нравится +40 Проголосовать: не нравится

    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.