-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleTimer.hpp
71 lines (69 loc) · 2.27 KB
/
SimpleTimer.hpp
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
70
71
#include <chrono>
#include <iostream>
namespace SimpleTimer
{
class Stopwatch
{
private:
const double NANOSECONDS = 1000000000.0;
const double MILLISECONDS = 1000000.0;
const double MICROSECONDS = 1000.0;
bool m_isRunning = false;
bool m_hasRun = false; //If the timer has run, get the last result.
std::chrono::time_point<std::chrono::high_resolution_clock> m_t1 = std::chrono::high_resolution_clock::now();
std::chrono::time_point<std::chrono::high_resolution_clock> m_t2 = std::chrono::high_resolution_clock::now();
public:
void Start()
{
m_isRunning = true;
m_hasRun = false;
m_t1 = std::chrono::high_resolution_clock::now();
}
void Stop()
{
if(m_isRunning)
{
m_isRunning = false;
m_hasRun = true;
m_t2 = std::chrono::high_resolution_clock::now();
}
else std::cout << "Error stopping timer: Timer not running\n";
}
double GetStopwatchSeconds()
{
if(m_hasRun) return std::chrono::duration_cast<std::chrono::nanoseconds>(m_t2 - m_t1).count() / NANOSECONDS;
else return -1;
}
double GetStopwatchMilliseconds()
{
if(m_hasRun) return std::chrono::duration_cast<std::chrono::nanoseconds>(m_t2 - m_t1).count() / MILLISECONDS;
else return -1;
}
double GetStopwatchMicroseconds()
{
if(m_hasRun) return std::chrono::duration_cast<std::chrono::nanoseconds>(m_t2 - m_t1).count() / MICROSECONDS;
else return -1;
}
double GetStopwatchNanoseconds()
{
if(m_hasRun) return std::chrono::duration_cast<std::chrono::nanoseconds>(m_t2 - m_t1).count();
else return -1;
}
};
class Timer
{
private:
Stopwatch t;
public:
Timer() { t.Start(); }
//Return time in seconds. Returns -1 if called before Start is called.
double GetTimerSeconds() { return t.GetStopwatchSeconds(); }
//Return time in nanoseconds. Returns -1 if called before Start is called.
double GetTimerMilliseconds() { return t.GetStopwatchMilliseconds(); }
//Return time in nanoseconds. Returns -1 if called before Start is called.
double GetTimerMicroseconds() { return t.GetStopwatchMicroseconds(); }
//Return time in nanoseconds. Returns -1 if called before Start is called.
double GetTimerNanoseconds() { return t.GetStopwatchNanoseconds(); }
double Stop() { t.Stop(); return t.GetStopwatchSeconds(); }
};
}