Mountain  1.0.0
Simple C++ 2D Game Framework
stopwatch.hpp
1 #pragma once
2 
3 #include <format>
4 #include <sstream>
5 
6 #include "Mountain/core.hpp"
7 #include "Mountain/utils/time_span.hpp"
8 
9 namespace Mountain
10 {
14  class MOUNTAIN_API Stopwatch
15  {
16  public:
17  [[nodiscard]]
18  static Stopwatch StartNew();
19 
20  [[nodiscard]]
21  static int64_t GetFrequency();
22  [[nodiscard]]
23  static int64_t GetTimestamp();
24  [[nodiscard]]
25  static TimeSpan GetElapsedTime(int64_t startingTimestamp);
26  [[nodiscard]]
27  static TimeSpan GetElapsedTime(int64_t startingTimestamp, int64_t endingTimestamp);
28 
29  void Start();
30  void Stop();
31  void Reset();
32  void Restart();
33 
34  GETTER(bool_t, IsRunning, m_IsRunning)
35 
36  [[nodiscard]]
37  TimeSpan GetElapsed() const;
38  [[nodiscard]]
39  int64_t GetElapsedTicks() const;
40  [[nodiscard]]
41  double_t GetElapsedMilliseconds() const;
42  [[nodiscard]]
43  double_t GetElapsedSeconds() const;
44 
45  friend std::ostream& operator<<(std::ostream& out, const Stopwatch& stopwatch);
46 
47  private:
48  static constexpr int64_t TicksPerMillisecond = 10000;
49  static constexpr int64_t TicksPerSecond = TicksPerMillisecond * 1000;
50 
51  static const double_t TickFrequency;
52 
53  int64_t m_StartTimestamp = 0;
54  int64_t m_Elapsed = 0;
55  bool_t m_IsRunning = false;
56 
57  [[nodiscard]]
58  int64_t GetRawElapsedTicks() const;
59  [[nodiscard]]
60  int64_t GetElapsedDateTimeTicks() const;
61  };
62 }
63 
65 template <>
66 struct std::formatter<Mountain::Stopwatch>
67 {
69  template <class ParseContext>
70  constexpr typename ParseContext::iterator parse(ParseContext& ctx)
71  {
72  auto it = ctx.begin();
73  if (it == ctx.end())
74  return it;
75 
76  if (*it != '}')
77  throw std::format_error("Invalid format args for Mountain::Stopwatch");
78 
79  return it;
80  }
81 
82  // ReSharper disable once CppMemberFunctionMayBeStatic
84  template <class FormatContext>
85  typename FormatContext::iterator format(const Mountain::Stopwatch& stopwatch, FormatContext& ctx) const
86  {
87  std::ostringstream out;
88 
89  out << stopwatch.GetElapsed();
90 
91  return std::ranges::copy(std::move(out).str(), ctx.out()).out;
92  }
93 };
C++ reimplementation of the .NET Stopwatch class.
Definition: stopwatch.hpp:14
FormatContext::iterator format(const Mountain::Stopwatch &stopwatch, FormatContext &ctx) const
Formats a string using the given instance of Mountain::Stopwatch, according to the given options in t...
Definition: stopwatch.hpp:85
constexpr ParseContext::iterator parse(ParseContext &ctx)
Parses the input formatting options.
Definition: stopwatch.hpp:70
C++ reimplementation of the .NET TimeSpan struct.
Definition: time_span.hpp:13
MATH_TOOLBOX std::ostream & operator<<(std::ostream &out, const Matrix &m)
Contains all declarations of the Mountain Framework.
Definition: audio.hpp:22