timeutil.c (1392B)
1 #include <stdbool.h> 2 #include <string.h> 3 #include <time.h> 4 5 #include "timeutil.h" 6 7 long 8 parse_latency(const char *timestamp) 9 { 10 struct tm tm; 11 struct timespec now; 12 const char *frac; 13 long millis = 0; 14 time_t sent; 15 16 if (timestamp == NULL || timestamp[0] == '\0') 17 return 0; 18 19 memset(&tm, 0, sizeof(tm)); 20 if ((frac = strptime(timestamp, "%Y-%m-%dT%H:%M:%S", &tm)) == NULL) 21 return 0; 22 23 if (*frac == '.') { 24 for (int i = 1; i <= 3 && frac[i] >= '0' && frac[i] <= '9'; i++) 25 millis = millis * 10 + (frac[i] - '0'); 26 while (millis > 0 && millis < 100) 27 millis *= 10; 28 } 29 30 if ((sent = timegm(&tm)) == (time_t)-1) 31 return 0; 32 if (clock_gettime(CLOCK_REALTIME, &now) != 0) 33 return 0; 34 35 return (now.tv_sec - sent) * 1000L + (now.tv_nsec / 1000000L) - millis; 36 } 37 38 void 39 schedule_heartbeat(struct timespec *next_heartbeat, const long heartbeat_ms) 40 { 41 clock_gettime(CLOCK_MONOTONIC, next_heartbeat); 42 next_heartbeat->tv_sec += heartbeat_ms / 1000; 43 next_heartbeat->tv_nsec += (heartbeat_ms % 1000) * 1000000L; 44 if (next_heartbeat->tv_nsec >= 1000000000L) { 45 next_heartbeat->tv_sec++; 46 next_heartbeat->tv_nsec -= 1000000000L; 47 } 48 } 49 50 bool 51 heartbeat_due(const struct timespec *next_heartbeat) 52 { 53 struct timespec now; 54 55 clock_gettime(CLOCK_MONOTONIC, &now); 56 57 return now.tv_sec > next_heartbeat->tv_sec 58 || (now.tv_sec == next_heartbeat->tv_sec 59 && now.tv_nsec >= next_heartbeat->tv_nsec); 60 }