-
Notifications
You must be signed in to change notification settings - Fork 4
/
timer.h
97 lines (75 loc) · 1.78 KB
/
timer.h
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* Allows to measure the time required to execute XXX() in the following way:
Timer t;
t.Start();
XXX();
t.Stop();
double seconds = t.Elapsed();
*/
#pragma once
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
#include <windows.h>
struct Timer
{
Timer()
{
// Initialize the resolution of the timer
if (!QueryPerformanceFrequency(&m_freq))
{
printf("QueryPerformanceFrequency failed!\n");
}
// Calculate the overhead of the timer in ticks
QueryPerformanceCounter(&m_start);
QueryPerformanceCounter(&m_stop);
m_overhead = m_stop.QuadPart - m_start.QuadPart;
}
void Start()
{
QueryPerformanceCounter(&m_start);
}
void Stop()
{
QueryPerformanceCounter(&m_stop);
}
// Returns elapsed time in seconds
double Elapsed()
{
return (m_stop.QuadPart - m_start.QuadPart - m_overhead) / double(m_freq.QuadPart);
}
private:
LARGE_INTEGER m_start;
LARGE_INTEGER m_stop;
LARGE_INTEGER m_freq;
LONGLONG m_overhead;
};
#else // this should handle any Unixes
#include <sys/time.h>
struct Timer
{
Timer()
{
// Calculate the timer overhead
overhead = 0;
Start();
Stop();
overhead = Elapsed();
}
void Start()
{
gettimeofday (&timerStart, NULL);
}
void Stop()
{
gettimeofday (&timerStop, NULL);
}
// Returns elapsed time in seconds
double Elapsed()
{
struct timeval timerElapsed;
timersub (&timerStop, &timerStart, &timerElapsed);
return (timerElapsed.tv_sec + timerElapsed.tv_usec/1e6 - overhead);
}
private:
struct timeval timerStart, timerStop;
double overhead;
};
#endif