]> arthur.barton.de Git - netdata.git/blob - src/clocks.c
Merge pull request #1313 from rlefevre/monotonic-clock
[netdata.git] / src / clocks.c
1 #include "common.h"
2
3 #ifndef HAVE_CLOCK_GETTIME
4 inline int clock_gettime(clockid_t clk_id, struct timespec *ts) {
5     struct timeval tv;
6     if(unlikely(gettimeofday(&tv, NULL) == -1))
7         return -1;
8     ts->tv_sec = tv.tv_sec;
9     ts->tv_nsec = tv.tv_usec * NSEC_PER_USEC;
10     return 0;
11 }
12 #endif
13
14 inline time_t now_realtime_sec(void) {
15     struct timespec ts;
16     if(unlikely(clock_gettime(CLOCK_REALTIME, &ts) == -1))
17         return 0;
18     return ts.tv_sec;
19 }
20
21 inline int now_realtime_timeval(struct timeval *tv) {
22     struct timespec ts;
23     if(unlikely(clock_gettime(CLOCK_REALTIME, &ts) == -1))
24         return -1;
25     tv->tv_sec = ts.tv_sec;
26     tv->tv_usec = ts.tv_nsec / NSEC_PER_USEC;
27     return 0;
28 }
29
30 inline usec_t now_realtime_usec(void) {
31     struct timespec ts;
32     if(unlikely(clock_gettime(CLOCK_REALTIME, &ts) == -1))
33         return 0;
34     return (usec_t)ts.tv_sec * USEC_PER_SEC + ts.tv_nsec / NSEC_PER_USEC;
35 }
36
37 inline time_t now_monotonic_sec(void) {
38     struct timespec ts;
39     if(unlikely(clock_gettime(CLOCK_MONOTONIC, &ts) == -1))
40         return 0;
41     return ts.tv_sec;
42 }
43
44 inline usec_t now_monotonic_usec(void) {
45     struct timespec ts;
46     if(unlikely(clock_gettime(CLOCK_MONOTONIC, &ts) == -1))
47         return 0;
48     return (usec_t)ts.tv_sec * USEC_PER_SEC + ts.tv_nsec / NSEC_PER_USEC;
49 }
50
51 inline time_t now_boottime_sec(void) {
52     struct timespec ts;
53     if(unlikely(clock_gettime(CLOCK_BOOTTIME, &ts) == -1))
54         return 0;
55     return ts.tv_sec;
56 }
57
58 inline usec_t now_boottime_usec(void) {
59     struct timespec ts;
60     if(unlikely(clock_gettime(CLOCK_BOOTTIME, &ts) == -1))
61         return 0;
62     return (usec_t)ts.tv_sec * USEC_PER_SEC + ts.tv_nsec / NSEC_PER_USEC;
63 }
64
65 inline usec_t timeval_usec(struct timeval *tv) {
66     return (usec_t)tv->tv_sec * USEC_PER_SEC + tv->tv_usec;
67 }
68
69 inline usec_t dt_usec(struct timeval *now, struct timeval *old) {
70     usec_t ts1 = timeval_usec(now);
71     usec_t ts2 = timeval_usec(old);
72     return (ts1 > ts2) ? (ts1 - ts2) : (ts2 - ts1);
73 }