8 months ago |
22 |
1 |
#include <time.h> | ||
2 |
|||||
7 months ago |
3 |
static inline struct timespec timespec_from_int64_ns(int64_t time_ns){ | |||
4 |
struct timespec r; | ||||
5 |
if (time_ns < 0){ | ||||
6 |
// Round negative times towards -infinity | ||||
7 |
time_ns = -time_ns; | ||||
8 |
r.tv_nsec = 999999999 - ((time_ns-1) % 1000000000); | ||||
9 |
r.tv_sec = -((time_ns+999999999) / 1000000000); | ||||
10 |
} else { | ||||
11 |
r.tv_nsec = time_ns % 1000000000; | ||||
12 |
r.tv_sec = time_ns / 1000000000; | ||||
13 |
} | ||||
14 |
return r; | ||||
15 |
} | ||||
16 |
|||||
17 |
|||||
18 |
static inline int64_t int64_ns_from_timespec(struct timespec time){ | ||||
19 |
return (int64_t)time.tv_sec * 1000000000 + time.tv_nsec; | ||||
20 |
} | ||||
21 |
|||||
22 |
|||||
8 months ago |
22 |
23 |
static inline bool timespec_lt(struct timespec a, struct timespec b){ | ||
24 |
return a.tv_sec < b.tv_sec || (a.tv_sec == b.tv_sec && a.tv_nsec < b.tv_nsec); | ||||
25 |
} | ||||
26 |
|||||
27 |
static inline bool timespec_lte(struct timespec a, struct timespec b){ | ||||
28 |
return a.tv_sec < b.tv_sec || (a.tv_sec == b.tv_sec && a.tv_nsec <= b.tv_nsec); | ||||
29 |
} | ||||
30 |
|||||
31 |
static inline bool timespec_eq(struct timespec a, struct timespec b){ | ||||
32 |
return a.tv_sec == b.tv_sec && a.tv_nsec == b.tv_nsec; | ||||
33 |
} | ||||
34 |
|||||
35 |
static inline bool timespec_gt(struct timespec a, struct timespec b){ | ||||
36 |
return timespec_lt(b, a); | ||||
37 |
} | ||||
38 |
|||||
39 |
static inline struct timespec timespec_sub(struct timespec a, struct timespec b){ | ||||
40 |
struct timespec r; | ||||
41 |
if (a.tv_nsec < b.tv_nsec){ | ||||
42 |
r.tv_nsec = 1000000000 + a.tv_nsec - b.tv_nsec; | ||||
43 |
r.tv_sec = a.tv_sec - b.tv_sec - 1; | ||||
44 |
} else { | ||||
45 |
r.tv_nsec = a.tv_nsec - b.tv_nsec; | ||||
46 |
r.tv_sec = a.tv_sec - b.tv_sec; | ||||
47 |
} | ||||
48 |
return r; | ||||
49 |
} | ||||
50 |
|||||
51 |
static inline bool timespec_gte(struct timespec a, struct timespec b){ | ||||
52 |
return timespec_lte(b, a); | ||||
53 |
} | ||||
54 |
|||||
55 |
static inline bool timespec_ne(struct timespec a, struct timespec b){ | ||||
56 |
return !timespec_eq(a, b); | ||||
57 |
} | ||||
58 |