-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmy_time.h
95 lines (83 loc) · 1.96 KB
/
my_time.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#ifndef MY_TIME_H
#define MY_TIME_H
#include <sys/time.h>
#include <assert.h>
#include <errno.h>
#include <time.h>
#if HAVE_CLOCK_GETTIME
static inline void
my_gettime(clockid_t clk_id, struct timespec *ts)
{
int res;
res = clock_gettime(clk_id, ts);
assert(res == 0);
}
#else
static inline void
my_gettime(int clk_id __attribute__((unused)), struct timespec *ts)
{
struct timeval tv;
int res;
res = gettimeofday(&tv, NULL);
assert(res == 0);
ts->tv_sec = tv.tv_sec;
ts->tv_nsec = tv.tv_usec * 1000;
}
#endif
static inline void
my_timespec_add(const struct timespec *a, struct timespec *b) {
b->tv_sec += a->tv_sec;
b->tv_nsec += a->tv_nsec;
while (b->tv_nsec >= 1000000000) {
b->tv_sec += 1;
b->tv_nsec -= 1000000000;
}
}
static inline void
my_timespec_sub(const struct timespec *a, struct timespec *b)
{
b->tv_sec -= a->tv_sec;
b->tv_nsec -= a->tv_nsec;
if (b->tv_nsec < 0) {
b->tv_sec -= 1;
b->tv_nsec += 1000000000;
}
}
/*
* Comparison function for struct timespec suitable for use with bsearch,
* qsort, etc. Returns an integer less than, equal to, or greater than zero
* if the first argument is considered to be respectively less than, equal
* to, or greater than the second.
*/
static inline int
my_timespec_cmp(const struct timespec *a, const struct timespec *b)
{
if (a->tv_sec < b->tv_sec)
return (-1);
else if (a->tv_sec > b->tv_sec)
return (1);
else if (a->tv_nsec < b->tv_nsec)
return (-1);
else if (a->tv_nsec > b->tv_nsec)
return (1);
else
return (0);
}
static inline double
my_timespec_to_double(const struct timespec *ts)
{
return (ts->tv_sec + ts->tv_nsec / 1E9);
}
static inline void
my_timespec_from_double(double seconds, struct timespec *ts) {
ts->tv_sec = (time_t) seconds;
ts->tv_nsec = (long) ((seconds - ((int) seconds)) * 1E9);
}
static inline void
my_nanosleep(const struct timespec *ts)
{
struct timespec rqt, rmt;
for (rqt = *ts; nanosleep(&rqt, &rmt) < 0 && errno == EINTR; rqt = rmt)
;
}
#endif /* MY_TIME_H */