1/**
2* hdr_time.h
3* Written by Michael Barker and Philip Orwig and released to the public domain,
4* as explained at http://creativecommons.org/publicdomain/zero/1.0/
5*/
6
7#include "hdr_time.h"
8
9#if defined(_WIN32) || defined(_WIN64)
10
11#if !defined(WIN32_LEAN_AND_MEAN)
12#define WIN32_LEAN_AND_MEAN
13#endif
14
15#include <windows.h>
16
17static int s_clockPeriodSet = 0;
18static double s_clockPeriod = 1.0;
19
20void hdr_gettime(hdr_timespec* t)
21{
22    LARGE_INTEGER num;
23    /* if this is distasteful, we can add in an hdr_time_init() */
24    if (!s_clockPeriodSet)
25    {
26        QueryPerformanceFrequency(&num);
27        s_clockPeriod = 1.0 / (double) num.QuadPart;
28        s_clockPeriodSet = 1;
29    }
30
31    QueryPerformanceCounter(&num);
32    double seconds = num.QuadPart * s_clockPeriod;
33    double integral;
34    double remainder = modf(seconds, &integral);
35
36    t->tv_sec  = (long) integral;
37    t->tv_nsec = (long) (remainder * 1000000000);
38}
39
40#elif defined(__APPLE__)
41
42#include <mach/clock.h>
43#include <mach/mach.h>
44
45
46void hdr_gettime(hdr_timespec* ts)
47{
48    clock_serv_t cclock;
49    mach_timespec_t mts;
50    host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
51    clock_get_time(cclock, &mts);
52    mach_port_deallocate(mach_task_self(), cclock);
53    ts->tv_sec = mts.tv_sec;
54    ts->tv_nsec = mts.tv_nsec;
55}
56
57
58void hdr_getnow(hdr_timespec* ts)
59{
60    hdr_gettime(ts);
61}
62
63#elif defined(__linux__) || defined(__CYGWIN__)
64
65
66void hdr_gettime(hdr_timespec* t)
67{
68    clock_gettime(CLOCK_MONOTONIC, (struct timespec*)t);
69}
70
71void hdr_getnow(hdr_timespec* t)
72{
73    clock_gettime(CLOCK_REALTIME, (struct timespec*)t);
74}
75
76#else
77
78#warning "Platform not supported\n"
79
80#endif
81
82double hdr_timespec_as_double(const hdr_timespec* t)
83{
84    double d = t->tv_sec;
85    return d + (t->tv_nsec / 1000000000.0);
86}
87
88void hdr_timespec_from_double(hdr_timespec* t, double value)
89{
90    int seconds = (int) value;
91    int milliseconds = (int) round((value - seconds) * 1000);
92
93    t->tv_sec = seconds;
94    t->tv_nsec = milliseconds * 1000000;
95}
96
97
98
99