@cryptotaxi247 / netdata-1 / commits / c032b7be6

introduce heartbeat API using monotonic clock

Signed-off-by: Rémi Lefèvre <remi.lefevre@parrot.com>

Rémi Lefèvre committed Dec 13, 2016 at 16:12 UTC c032b7be6773ba76c0560bfed83d2b0b86b267d6
2 files changed +49 -2
src/clocks.c
+35
@@ -71,3 +71,38 @@ inline usec_t dt_usec(struct timeval *now, struct timeval *old) {
71 usec_t ts2 = timeval_usec(old);
72 return (ts1 > ts2) ? (ts1 - ts2) : (ts2 - ts1);
73 }
74 +
75 +inline void heartbeat_init(heartbeat_t *hb)
76 +{
77 + *hb = 0ULL;
78 +}
79 +
80 +usec_t heartbeat_next(heartbeat_t *hb, usec_t tick)
81 +{
82 + heartbeat_t now = now_monotonic_usec();
83 + usec_t next = now - (now % tick) + tick;
84 +
85 + while(now < next) {
86 + sleep_usec(next - now);
87 + now = now_monotonic_usec();
88 + }
89 +
90 + if(likely(*hb != 0ULL)) {
91 + usec_t dt = now - *hb;
92 + *hb = now;
93 + if(unlikely(dt / tick > 1))
94 + error("heartbeat missed between %llu usec and %llu usec", *hb, now);
95 + return dt;
96 + }
97 + else {
98 + *hb = now;
99 + return 0ULL;
100 + }
101 +}
102 +
103 +inline usec_t heartbeat_dt_usec(heartbeat_t *hb)
104 +{
105 + if(!*hb)
106 + return 0ULL;
107 + return now_monotonic_usec() - *hb;
108 +}
src/clocks.h
+14 -2
@@ -12,6 +12,10 @@ struct timespec {
12 typedef int clockid_t;
13 #endif
14
15 +typedef unsigned long long usec_t;
16 +
17 +typedef usec_t heartbeat_t;
18 +
19 #ifndef HAVE_CLOCK_GETTIME
20 int clock_gettime(clockid_t clk_id, struct timespec *ts);
21 #endif
@@ -35,8 +39,6 @@ int clock_gettime(clockid_t clk_id, struct timespec *ts);
39 #endif
40 #endif
41
38 -typedef unsigned long long usec_t;
39 -
42 #define NSEC_PER_SEC 1000000000ULL
43 #define NSEC_PER_MSEC 1000000ULL
44 #define NSEC_PER_USEC 1000ULL
@@ -89,4 +91,14 @@ extern usec_t now_boottime_usec(void);
91 extern usec_t timeval_usec(struct timeval *ts);
92 extern usec_t dt_usec(struct timeval *now, struct timeval *old);
93
94 +extern void heartbeat_init(heartbeat_t *hb);
95 +
96 +/* Sleeps until next multiple of tick using monotonic clock.
97 + * Returns elapsed time in microseconds since previous heartbeat
98 + */
99 +extern usec_t heartbeat_next(heartbeat_t *hb, usec_t tick);
100 +
101 +/* Returns elapsed time in microseconds since last heartbeat */
102 +extern usec_t heartbeat_dt_usec(heartbeat_t *hb);
103 +
104 #endif /* NETDATA_CLOCKS_H */