PageRenderTime 20ms CodeModel.GetById 15ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 1ms

/src/rt/sync/timer.cpp

http://github.com/jruderman/rust
C++ | 75 lines | 63 code | 11 blank | 1 comment | 4 complexity | 55b444767dc1277e314699718efd1eb1 MD5 | raw file
 1#include "../rust_globals.h"
 2#include "timer.h"
 3
 4#if defined(__APPLE__)
 5#include <mach/mach_time.h>
 6#endif
 7
 8uint64_t ns_per_s = 1000000000LL;
 9
10timer::timer() {
11#if __WIN32__
12    _ticks_per_s = 0LL;
13    // FIXME (#2675): assert this works or have a workaround.
14    QueryPerformanceFrequency((LARGE_INTEGER *)&_ticks_per_s);
15    if (_ticks_per_s == 0LL) {
16      _ticks_per_s = 1LL;
17    }
18#endif
19    reset_us(0);
20}
21
22void
23timer::reset_us(uint64_t timeout_us) {
24    _start_us = time_us();
25    _timeout_us = timeout_us;
26}
27
28uint64_t
29timer::elapsed_us() {
30    return time_us() - _start_us;
31}
32
33double
34timer::elapsed_ms() {
35    return (double) elapsed_us() / 1000.0;
36}
37
38int64_t
39timer::remaining_us() {
40    return _timeout_us - elapsed_us();
41}
42
43bool
44timer::has_timed_out() {
45    return remaining_us() <= 0;
46}
47
48uint64_t
49timer::time_ns() {
50#ifdef __APPLE__
51    uint64_t time = mach_absolute_time();
52    mach_timebase_info_data_t info = {0, 0};
53    if (info.denom == 0) {
54        mach_timebase_info(&info);
55    }
56    uint64_t time_nano = time * (info.numer / info.denom);
57    return time_nano;
58#elif __WIN32__
59    uint64_t ticks;
60    QueryPerformanceCounter((LARGE_INTEGER *)&ticks);
61    return ((ticks * ns_per_s) / _ticks_per_s);
62#else
63    timespec ts;
64    clock_gettime(CLOCK_MONOTONIC, &ts);
65    return (ts.tv_sec * ns_per_s + ts.tv_nsec);
66#endif
67}
68
69uint64_t
70timer::time_us() {
71    return time_ns() / 1000;
72}
73
74timer::~timer() {
75}