Engine
Raylib based game framework
Loading...
Searching...
No Matches
Timer.h
1#pragma once
2
3#include "Log.h"
4
5#include "Types.h"
6
7#include <deque>
8
9class Timer
10{
11public:
12
13 Timer()
14 {
15 }
16
17 Timer(const std::string& name)
18 {
19 m_name = name;
20 m_start = std::chrono::steady_clock::now();
21 }
22
23 ~Timer()
24 {
25 if (!m_done)
26 {
27 Stop();
28 }
29 }
30
31 void Start()
32 {
33 Start("");
34 }
35
36 void Start(const std::string& name)
37 {
38 Stop();
39
40 m_name = name;
41 m_start = std::chrono::steady_clock::now();
42
43 m_done = false;
44 }
45
46 double Stop()
47 {
48 return Stop("");
49 }
50
51 double Stop(const std::string& text)
52 {
53 if (m_done)
54 {
55 return 0.0;
56 }
57
58 m_end = std::chrono::steady_clock::now();
59 m_done = true;
60
61 double microseconds = std::chrono::duration_cast<std::chrono::microseconds>(m_end - m_start).count();
62 if (!m_name.empty())
63 {
64 Log(m_name, " took: ", microseconds * 0.001, " ms ", text);
65 }
66
67 return microseconds * 0.001;
68 }
69
70private:
71
72 std::chrono::time_point<std::chrono::steady_clock> m_start;
73 std::chrono::time_point<std::chrono::steady_clock> m_end;
74
75 bool m_done = true;
76
77 std::string m_name;
78};
79
80template <typename T>
82{
83public:
84
85 RollingAverage(const u64 samples = 100)
86 {
87 m_sampleCount = samples;
88 }
89
90 void Add(const T value)
91 {
92 m_samples.push_back(value);
93
94 if (m_samples.size() > m_sampleCount)
95 {
96 m_samples.pop_front();
97 }
98 }
99
100 void operator+=(const T value)
101 {
102 Add(value);
103 }
104
105 T Average() const
106 {
107 if (m_samples.empty())
108 {
109 return 0;
110 }
111
112 T sum = 0;
113
114 for (const float value : m_samples)
115 {
116 sum += value;
117 }
118
119 return sum / m_samples.size();
120 }
121
122private:
123
124 std::deque<T> m_samples;
125 u64 m_sampleCount;
126};
Definition Timer.h:82
Definition Timer.h:10