r-type  0.0.0
R-Type main
Loading...
Searching...
No Matches
Clock.hpp
Go to the documentation of this file.
1///
2/// @file Clock.hpp
3/// @brief This file contains the Clock class
4/// @namespace utl
5///
6
7#pragma once
8
9#include <chrono>
10#include <ostream>
11
12namespace utl
13{
14
15 ///
16 /// @class Clock
17 /// @brief Class for clock
18 /// @namespace utl
19 ///
20 class Clock
21 {
22
23 public:
24 using TimePoint = std::chrono::time_point<std::chrono::high_resolution_clock>;
25
26 explicit Clock(const bool startNow = true) : m_start{startNow ? now() : TimePoint()}, m_pausedDuration{0} {}
27 ~Clock() = default;
28
29 Clock(const Clock &) = delete;
30 Clock &operator=(const Clock &) = delete;
31 Clock(Clock &&) = delete;
32 Clock &operator=(Clock &&) = delete;
33
34 friend std::ostream &operator<<(std::ostream &os, const Clock &clock)
35 {
36 os << "Elapsed time: " << clock.getDeltaSeconds() << " seconds";
37 return os;
38 }
39
40 static TimePoint now() { return std::chrono::high_resolution_clock::now(); }
41 void restart()
42 {
43 m_start = now();
45 m_isPaused = false;
46 }
47 void pause()
48 {
49 if (!m_isPaused)
50 {
51 m_pausedTime = now();
52 m_isPaused = true;
53 }
54 }
55 void resume()
56 {
57 if (m_isPaused)
58 {
60 m_isPaused = false;
61 }
62 }
63 [[nodiscard]] float getDeltaSeconds() const
64 {
65 if (m_isPaused)
66 {
67 return std::chrono::duration<float>(m_pausedTime - m_start - m_pausedDuration).count();
68 }
69 return std::chrono::duration<float>(now() - m_start - m_pausedDuration).count();
70 }
71
72 template <typename Duration = std::chrono::seconds> [[nodiscard]] auto getElapsed() const
73 {
74 return std::chrono::duration_cast<Duration>(now() - m_start - m_pausedDuration);
75 }
76
77 private:
78 using Duration = std::chrono::high_resolution_clock::duration;
79
83 bool m_isPaused{false};
84
85 }; // class Clock
86
87} // namespace utl
Class for clock.
Definition Clock.hpp:21
Duration m_pausedDuration
Definition Clock.hpp:82
TimePoint m_start
Definition Clock.hpp:80
Clock & operator=(Clock &&)=delete
Clock(const bool startNow=true)
Definition Clock.hpp:26
std::chrono::time_point< std::chrono::high_resolution_clock > TimePoint
Definition Clock.hpp:24
void restart()
Definition Clock.hpp:41
bool m_isPaused
Definition Clock.hpp:83
float getDeltaSeconds() const
Definition Clock.hpp:63
std::chrono::high_resolution_clock::duration Duration
Definition Clock.hpp:78
void resume()
Definition Clock.hpp:55
Clock(Clock &&)=delete
Clock(const Clock &)=delete
TimePoint m_pausedTime
Definition Clock.hpp:81
void pause()
Definition Clock.hpp:47
friend std::ostream & operator<<(std::ostream &os, const Clock &clock)
Definition Clock.hpp:34
auto getElapsed() const
Definition Clock.hpp:72
static TimePoint now()
Definition Clock.hpp:40
Clock & operator=(const Clock &)=delete
~Clock()=default