Lodestar
An integrated real-time control package in C++
Metronome.hpp
1 //
2 // Created by Hamza El-Kebir on 6/13/21.
3 //
4 
5 #ifndef LODESTAR_METRONOME_HPP
6 #define LODESTAR_METRONOME_HPP
7 
8 #include <chrono>
9 #include "TimeResolution.hpp"
10 #include "TimeDuration.hpp"
11 
12 namespace ls {
13  namespace time {
14  template <TimeDuration TDuration = TimeDuration::milliseconds, TimeResolution TTimeRes = TimeResolution::HighResolution>
15  class Metronome {};
16 
17  template <TimeDuration TDuration>
18  class Metronome<TDuration, TimeResolution::HighResolution> {
19  public:
20  using Clock = std::chrono::high_resolution_clock;
21  Metronome() : period_(100 * (int) TDuration) {
22  last_ = Clock::now();
23  }
24 
25  Metronome(size_t period) : period_(period * (int) TDuration) {
26  last_ = Clock::now();
27  }
28 
29  bool hasElapsed() {
30  auto current = Clock::now();
31 
32  if (std::chrono::duration_cast<std::chrono::nanoseconds>(current - last_).count() >= period_) {
33  last_ = current;
34 
35  return true;
36  } else {
37  return false;
38  }
39  }
40 
41  double timeElapsed() const {
42  auto current = Clock::now();
43 
44  return (double) std::chrono::duration_cast<std::chrono::nanoseconds>(current - last_).count() / (int) TDuration;
45  }
46  protected:
47  std::chrono::time_point<Clock, std::chrono::nanoseconds> last_;
48  size_t period_;
49  };
50  }
51 }
52 
53 #endif //LODESTAR_METRONOME_HPP
ls::time::Metronome
Definition: Metronome.hpp:15
ls
Main Lodestar code.
Definition: BilinearTransformation.hpp:12