-
Notifications
You must be signed in to change notification settings - Fork 113
/
timer.cpp
99 lines (81 loc) · 1.66 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#ifdef _WIN32
#include <windows.h>
#elif __APPLE__
#include <mach/mach_time.h>
#endif
#include <timer.h>
namespace timer
{
Timer::Timer()
{
start();
}
void Timer::start()
{
beginning = rdtsc();
beginningS = ( beginning + 0.0 ) * 1.0e-9;
running = true;
}
void Timer::stop()
{
ending = rdtsc();
endingS = ( ending + 0.0 ) * 1.0e-9;
running = false;
}
Timer::Cycle Timer::cycles() const
{
if( running )
{
return ( rdtsc() - beginning );
}
else
{
return ( ending - beginning );
}
}
Timer::Second Timer::seconds() const
{
if( running )
{
return ( ( ( rdtsc() + 0.0 ) * 1.0e-9 ) - beginningS );
}
else
{
return endingS - beginningS;
}
}
Timer::Second Timer::absolute() const
{
if( running )
{
return ( ( ( rdtsc() + 0.0 ) * 1.0e-9 ) );
}
else
{
return endingS;
}
}
Timer::Cycle Timer::rdtsc()
{
#ifdef _WIN32
Cycle cycles = 0;
Cycle frequency = 0;
QueryPerformanceFrequency((LARGE_INTEGER*) &frequency);
QueryPerformanceCounter((LARGE_INTEGER*) &cycles);
return cycles / frequency;
#elif __APPLE__
uint64_t absolute_time = mach_absolute_time();
mach_timebase_info_data_t info = {0,0};
if (info.denom == 0) mach_timebase_info(&info);
uint64_t elapsednano = absolute_time * (info.numer / info.denom);
timespec spec;
spec.tv_sec = elapsednano * 1e-9;
spec.tv_nsec = elapsednano - (spec.tv_sec * 1e9);
return spec.tv_nsec + (Cycle)spec.tv_sec * 1e9;
#else
timespec spec;
clock_gettime( CLOCK_REALTIME, &spec );
return spec.tv_nsec + (Cycle)spec.tv_sec * 1e9;
#endif
}
}