From 005cd3b630fcf0f3870f426a0db5e54400a59ef9 Mon Sep 17 00:00:00 2001 From: Johannes Stoelp Date: Mon, 3 Jul 2023 22:17:34 +0200 Subject: timer: add simple linux watchclock timer --- timer.h | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 timer.h (limited to 'timer.h') diff --git a/timer.h b/timer.h new file mode 100644 index 0000000..933c02c --- /dev/null +++ b/timer.h @@ -0,0 +1,52 @@ +#include +#include + +namespace timer { +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 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(m_nanos) / 1000.0; + } + + private: + static constexpr clockid_t kClock = CLOCK_MONOTONIC_RAW; + + timespec m_start{}; + std::uint64_t m_nanos{0}; +}; + +struct scoped_timer { + explicit scoped_timer(timer& t) : m_timer(t) { + m_timer.start(); + } + + ~scoped_timer() { + m_timer.stop(); + } + + private: + timer& m_timer; +}; + +} // namespace timer -- cgit v1.2.3