about summary refs log tree commit diff
path: root/src/rt/sync/timer.cpp
blob: e45dd63331410feb3a1bc3af8d8c5c2e22c8ac47 (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
#include "../globals.h"
#include "timer.h"

#if defined(__APPLE__)
#include <mach/mach_time.h>
#endif

timer::timer() {
    reset(0);
#if __WIN32__
    uint64_t ticks_per_second;
    QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second);
    _ticks_per_us = ticks_per_second / 1000000;
#endif
}

void
timer::reset(uint64_t timeout) {
    _start = get_time();
    _timeout = timeout;
}

uint64_t
timer::get_elapsed_time() {
    return get_time() - _start;
}

int64_t
timer::get_timeout() {
    return _timeout - get_elapsed_time();
}

bool
timer::has_timed_out() {
    return get_timeout() <= 0;
}

uint64_t
timer::get_time() {
#ifdef __APPLE__
    uint64_t time = mach_absolute_time();
    mach_timebase_info_data_t info = {0, 0};
    if (info.denom == 0) {
        mach_timebase_info(&info);
    }
    uint64_t time_nano = time * (info.numer / info.denom);
    return time_nano / 1000;
#elif __WIN32__
    uint64_t ticks;
    QueryPerformanceCounter((LARGE_INTEGER *)&ticks);
    return ticks / _ticks_per_us;
#else
    timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return (ts.tv_sec * 1000000000LL + ts.tv_nsec) / 1000;
#endif
}

timer::~timer() {
    // Nop.
}