File: timer.h

package info (click to toggle)
cppnumericalsolvers 1.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 372 kB
  • sloc: cpp: 2,694; python: 236; sh: 20; makefile: 10
file content (90 lines) | stat: -rw-r--r-- 1,727 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#ifndef TIMER_H
#define TIMER_H

#include <chrono>
#include <stdexcept>

namespace cppoptlib {

template<typename C = std::chrono::high_resolution_clock>
class timer
{
   std::chrono::time_point<C> start_v;
   std::chrono::time_point<C> pause_v;
   std::chrono::time_point<C> end_v;

  bool stopped;
  bool paused;

public:
  explicit timer() : stopped(false), paused(false) {
    start_v = C::now();
  }
  ~timer() {}

  /**
   * @brief start stopwatch
   * @details [long description]
   */
  void start() {
    start_v = C::now();
    paused = false;
    stopped = false;
  }

  /**
   * @brief break stopwatch, but allows resuming
   * @details [long description]
   */
  void pause() {
    pause_v = C::now();
    paused = true;
  }

  void resume() {
    if(stopped)
      throw std::runtime_error("cannot resume a stopped timer");
    start_v += C::now() - pause_v;
    paused = false;
    stopped = false;
  }

  void stop() {
    end_v = C::now();
    stopped = true;
  }

  template<typename U = std::chrono::milliseconds>
  typename U::rep elapsed() const
  {
    /*
    example:
      cns::timer t;
      t.sart();
      // do something
      t.stop();
      std::cout << t.elapsed<UNIT>() << std::endl;

    where UNIT can be:
    std::chrono::nanoseconds
    std::chrono::microseconds
    std::chrono::milliseconds
    std::chrono::seconds
    std::chrono::minutes
    std::chrono::hours
    */

      return
        (stopped) ?
          std::chrono::duration_cast<U>(end_v - start_v).count() :
          (paused) ?
            std::chrono::duration_cast<U>(pause_v - start_v).count() :
            std::chrono::duration_cast<U>(C::now() - start_v).count();;
  }

};

}
/* namespace cns */

#endif /* TIMER_H */