aboutsummaryrefslogtreecommitdiff
path: root/timer.h
blob: 307f0ac36876b51120d490ae7ed905c0c6a5633a (plain) (blame)
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
#ifndef UTILS_TIMER_H
#define UTILS_TIMER_H

#include <cstdint>
#include <ctime>

namespace timer {
/// A minimal Linux watch clock.
struct timer {
  constexpr timer() = default;

  void start() {
    clock_gettime(kClock, &m_start);
  }

  void stop() {
    timespec end;
    clock_gettime(kClock, &end);

    m_nanos += ((end.tv_sec - m_start.tv_sec) * 1000000000ull) +
               (end.tv_nsec - m_start.tv_nsec);
  }

  constexpr void reset() {
    m_nanos = 0;
  }

  constexpr double as_sec() const {
    return as_msec() / 1000.0;
  }

  constexpr double as_msec() const {
    return as_usec() / 1000.0;
  }

  constexpr double as_usec() const {
    return static_cast<double>(m_nanos) / 1000.0;
  }

 private:
  static constexpr clockid_t kClock = CLOCK_MONOTONIC_RAW;

  timespec m_start{};
  std::uint64_t m_nanos{0};
};

/// A scoped timer to automatically start / stop a watch clock in the scope the
/// scoped_timer lives.
struct scoped_timer {
  explicit scoped_timer(timer& t) : m_timer(t) {
    m_timer.start();
  }

  ~scoped_timer() {
    m_timer.stop();
  }

  scoped_timer(const scoped_timer&) = delete;
  scoped_timer& operator=(const scoped_timer&) = delete;
  scoped_timer(scoped_timer&&) = delete;
  scoped_timer& operator=(scoped_timer&&) = delete;

 private:
  timer& m_timer;
};

}  // namespace timer

#endif