/
timer.cpp
82 lines (67 loc) · 1.69 KB
/
timer.cpp
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
72
73
74
75
76
77
78
79
80
81
82
/**
* @file timer.cpp
* @brief Frame timer
* @author Andrew Fox (arfox)
*/
#ifdef _WIN32
#include <windows.h>
#else
#include <SDL/SDL.h>
#endif
#include <cassert>
#include "timer.h"
Timer::Timer()
: TicksPerSecond(0),
Count(0),
PrevTicks(0),
Length(0),
SectionStart(0),
SectionEnd(0),
SectionTiming(false),
lastSectionTime(0.0) {
#ifdef _WIN32
QueryPerformanceFrequency((LARGE_INTEGER*)&TicksPerSecond);
#else
TicksPerSecond = 1000; // SDL_GetTicks has resolution on the order of a MS
Count = SDL_GetTicks();
#endif
PrevTicks = Count;
}
Timer::ticks_t Timer::getTicks() {
ticks_t count;
#ifdef _WIN32
QueryPerformanceCounter((LARGE_INTEGER*)&count);
#else
count = SDL_GetTicks();
#endif
return count;
}
void Timer::update() {
Count = getTicks();
Length = Count - PrevTicks;
PrevTicks = Count; // save for next time
}
double Timer::getLengthSeconds() const {
return (double)Length / (double)TicksPerSecond;
}
double Timer::getElapsedTimeMS() const {
ticks_t Now, ElapsedTicks;
double ElapsedSeconds, ElapsedMilliseconds;
Now = getTicks();
ElapsedTicks = Now - PrevTicks;
ElapsedSeconds = ElapsedTicks / (double)TicksPerSecond;
ElapsedMilliseconds = ElapsedSeconds * 1000.0;
return ElapsedMilliseconds;
}
void Timer::beginTiming() {
assert(!SectionTiming && "Cannot nest timing blocks with a single Timer object. Use another timer!");
SectionTiming = true;
SectionStart = getTicks();
}
double Timer::endTiming() {
assert(SectionTiming && "Cannot nest timing blocks with a single Timer object. Use another timer!");
SectionTiming = false;
SectionEnd = getTicks();
lastSectionTime = (double)(SectionEnd - SectionStart) / TicksPerSecond * 1000.0;
return lastSectionTime;
}