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

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

Hello Codeforces,

It is sometimes required in competitive programming problems at run-time to measure elapsed time between two events on a real-time scale such as milliseconds. It is possible in C++ to do that using the std::chrono library classes and functions. The following is a C++ timer class that simplifies doing this operation.

#include <bits/stdc++.h>
using namespace std;
using namespace chrono;

class timer: high_resolution_clock {
    const time_point start_time;
public:
    timer(): start_time(now()) {}
    rep elapsed_time() const { return duration_cast<milliseconds>(now()-start_time).count(); } };

The timer class inherits the base class std::chrono::high_resolution_clock. A private std::chrono::time_point constant variable start_time is used to store the initial point of time at which the timer object was created using the class constructor function. The class features a constant public member function elapsed_time() whose call returns a non-negative integer which measures the elapsed time in milliseconds since the creation of the timer object.

The following is a sample example for using the timer class.

const int T = 1000;
timer t; // create a timer object

int main() {
    while (t.elapsed_time() < T) {
        // do something
    }
}

Your constructive comments and feedback are welcome and appreciated.

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

»
6 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

How can it help in a contest?

  • »
    »
    6 лет назад, скрыть # ^ |
    Rev. 2  
    Проголосовать: нравится 0 Проголосовать: не нравится

    The while loop in the sample program stops when elapsed time is larger than or equal to T. Suppose that T is set to a value that is slightly smaller than the time-limit for the problem. It should be then possible to guarantee that the submitted solution does not get TLE (Time-Limit Exceed) Verdict.

»
6 лет назад, скрыть # |
 
Проголосовать: нравится +1 Проголосовать: не нравится

Probably the simplest way to kill your solution is to make system function calls in a loop :)