blob: 55eb200d747251997b4d216681955de8534054a9 (
plain)
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
|
/* Copyright (c) 2014-2015, Stanislaw Halik <sthalik@misaki.pl>
* Permission to use, copy, modify, and/or distribute this
* software for any purpose with or without fee is hereby granted,
* provided that the above copyright notice and this permission
* notice appear in all copies.
*/
#undef NDEBUG
#include "timer.hpp"
#include <cassert>
#include <cmath>
#include <QDebug>
using time_type = Timer::time_type;
Timer::Timer()
{
start();
}
void Timer::start()
{
gettime(&state);
}
struct timespec Timer::gettime_() const
{
struct timespec ts{};
gettime(&ts);
ts.tv_sec -= state.tv_sec;
ts.tv_nsec -= state.tv_nsec;
return ts;
}
// nanoseconds
time_type Timer::elapsed_nsecs() const
{
struct timespec delta = gettime_();
return (time_type)delta.tv_sec * 1000000000 + (time_type)delta.tv_nsec;
}
// milliseconds
double Timer::elapsed_ms() const
{
struct timespec delta = gettime_();
return delta.tv_sec * 1000 + delta.tv_nsec * 1e-6;
}
double Timer::elapsed_seconds() const
{
struct timespec delta = gettime_();
return delta.tv_sec + delta.tv_nsec * 1e-9;
}
// --
// platform-specific code starts here
// --
#if defined (_WIN32)
# include <windows.h>
static auto otr_get_clock_frequency()
{
LARGE_INTEGER freq{};
BOOL ret = QueryPerformanceFrequency(&freq);
assert(ret && "QueryPerformanceFrequency failed");
return freq.QuadPart;
}
void Timer::gettime(timespec* ts)
{
static const unsigned long long freq = otr_get_clock_frequency();
LARGE_INTEGER d;
BOOL ret = QueryPerformanceCounter(&d);
assert(ret && "QueryPerformanceCounter failed");
auto part = (long long)std::roundl((d.QuadPart * 1000000000.L) / freq);
ts->tv_sec = d.QuadPart/freq;
ts->tv_nsec = part % 1000000000;
}
#elif defined __MACH__
# include <inttypes.h>
# include <mach/mach_time.h>
static mach_timebase_info_data_t otr_get_mach_frequency()
{
mach_timebase_info_data_t timebase_info;
(void)mach_timebase_info(&timebase_info);
return timebase_info;
}
void Timer::gettime(timespec* ts)
{
static const mach_timebase_info_data_t timebase_info = otr_get_mach_frequency();
uint64_t state, nsec;
state = mach_absolute_time();
nsec = state * timebase_info.numer / timebase_info.denom;
ts->tv_sec = nsec / 1000000000UL;
ts->tv_nsec = nsec % 1000000000UL;
}
#else
void Timer::gettime(timespec* ts)
{
[[maybe_unused]] int error = clock_gettime(CLOCK_MONOTONIC, ts);
assert(error == 0 && "clock_gettime failed");
};
#endif
// common
|