ctrl-utils
timer.h
1 
10 #ifndef CTRL_UTILS_TIMER_H_
11 #define CTRL_UTILS_TIMER_H_
12 
13 #include <chrono> // std::chrono
14 #include <thread> // std::this_thread
15 
16 namespace ctrl_utils {
17 
25 class Timer {
26  public:
27  using Seconds = std::chrono::duration<double>;
28  using Clock = std::chrono::steady_clock;
29 
33  Timer() {}
34 
41  Timer(double frequency) { set_freq(frequency); }
42 
47  double freq() const { return 1 / dt(); }
48 
52  void set_freq(double frequency) { set_dt(1. / frequency); }
53 
58  double dt() const {
59  return std::chrono::duration_cast<Seconds>(dt_interval_).count();
60  }
61 
65  void set_dt(double dt) {
66  dt_interval_ = std::chrono::duration_cast<Clock::duration>(Seconds(dt));
67  }
68 
73  double time(bool update = false) const {
74  if (update) t_curr_ = Clock::now();
75  return std::chrono::duration_cast<Seconds>(t_curr_.time_since_epoch())
76  .count();
77  }
78 
83  double time_elapsed(bool update = false) const {
84  if (update) t_curr_ = Clock::now();
85  return std::chrono::duration_cast<Seconds>(t_curr_ - t_start_).count();
86  }
87 
92  double time_sim() const {
93  return std::chrono::duration_cast<Seconds>(t_next_ - t_start_).count();
94  }
95 
99  double average_freq() const { return (num_iters() - 1) / time_elapsed(); }
100 
105  unsigned long long num_iters() const { return num_iters_; }
106 
112  void Reset() {
113  num_iters_ = 0;
114  t_start_ = Clock::now();
115  t_curr_ = t_start_;
116  t_next_ = t_start_ + dt_interval_;
117  }
118 
124  void Sleep() {
125  t_curr_ = Clock::now();
126  if (!initialized_) {
127  t_start_ = t_curr_;
128  t_next_ = t_curr_;
129  initialized_ = true;
130  }
131 
132  if (t_curr_ < t_next_) {
133  std::this_thread::sleep_for(t_next_ - t_curr_);
134  }
135  t_next_ += dt_interval_;
136  ++num_iters_;
137  }
138 
139  private:
141  Clock::time_point t_start_;
142  mutable Clock::time_point t_curr_;
143  Clock::time_point t_next_;
144  unsigned long long num_iters_ = 0;
145 
146  bool initialized_ = false;
147  Clock::duration dt_interval_ = std::chrono::milliseconds(1);
149 };
150 
151 } // namespace ctrl_utils
152 
153 #endif // CTRL_UTILS_TIMER_H_
Definition: timer.h:25
double average_freq() const
Definition: timer.h:99
Timer(double frequency)
Definition: timer.h:41
void set_freq(double frequency)
Definition: timer.h:52
double time(bool update=false) const
Definition: timer.h:73
unsigned long long num_iters() const
Definition: timer.h:105
void Sleep()
Definition: timer.h:124
double freq() const
Definition: timer.h:47
Timer()
Definition: timer.h:33
void set_dt(double dt)
Definition: timer.h:65
void Reset()
Definition: timer.h:112
double time_elapsed(bool update=false) const
Definition: timer.h:83
double dt() const
Definition: timer.h:58
double time_sim() const
Definition: timer.h:92
Definition: ctrl_utils.cc:18