1 #ifndef MY_TIME_H
2 #define MY_TIME_H
3
4 #include <sys/time.h>
5 #include <assert.h>
6 #include <errno.h>
7 #include <time.h>
8
9 #if HAVE_CLOCK_GETTIME
10 static inline void
my_gettime(clockid_t clk_id,struct timespec * ts)11 my_gettime(clockid_t clk_id, struct timespec *ts)
12 {
13 int res;
14 res = clock_gettime(clk_id, ts);
15 assert(res == 0);
16 }
17 #else
18 static inline void
my_gettime(int clk_id,struct timespec * ts)19 my_gettime(int clk_id __attribute__((unused)), struct timespec *ts)
20 {
21 struct timeval tv;
22 int res;
23
24 res = gettimeofday(&tv, NULL);
25 assert(res == 0);
26
27 ts->tv_sec = tv.tv_sec;
28 ts->tv_nsec = tv.tv_usec * 1000;
29 }
30 #endif
31
32 static inline void
my_timespec_add(const struct timespec * a,struct timespec * b)33 my_timespec_add(const struct timespec *a, struct timespec *b) {
34 b->tv_sec += a->tv_sec;
35 b->tv_nsec += a->tv_nsec;
36 while (b->tv_nsec >= 1000000000) {
37 b->tv_sec += 1;
38 b->tv_nsec -= 1000000000;
39 }
40 }
41
42 static inline void
my_timespec_sub(const struct timespec * a,struct timespec * b)43 my_timespec_sub(const struct timespec *a, struct timespec *b)
44 {
45 b->tv_sec -= a->tv_sec;
46 b->tv_nsec -= a->tv_nsec;
47 if (b->tv_nsec < 0) {
48 b->tv_sec -= 1;
49 b->tv_nsec += 1000000000;
50 }
51 }
52
53 static inline double
my_timespec_to_double(const struct timespec * ts)54 my_timespec_to_double(const struct timespec *ts)
55 {
56 return (ts->tv_sec + ts->tv_nsec / 1E9);
57 }
58
59 static inline void
my_timespec_from_double(double seconds,struct timespec * ts)60 my_timespec_from_double(double seconds, struct timespec *ts) {
61 ts->tv_sec = (time_t) seconds;
62 ts->tv_nsec = (long) ((seconds - ((int) seconds)) * 1E9);
63 }
64
65 static inline void
my_nanosleep(const struct timespec * ts)66 my_nanosleep(const struct timespec *ts)
67 {
68 struct timespec rqt, rmt;
69
70 for (rqt = *ts; nanosleep(&rqt, &rmt) < 0 && errno == EINTR; rqt = rmt)
71 ;
72 }
73
74 #endif /* MY_TIME_H */
75