-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtime-util.h
83 lines (71 loc) · 2.26 KB
/
time-util.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
#ifndef TIME_UTIL_H
#define TIME_UTIL_H
#include <assert.h>
#include <stdatomic.h>
#include <time.h>
#define TIME_UTIL_CLOCK CLOCK_THREAD_CPUTIME_ID
static inline int timespec_diff (struct timespec *,
const struct timespec *,
const struct timespec *);
#define BEGIN_TIME(p) \
do \
{ \
atomic_thread_fence (memory_order_seq_cst); \
int clock_gettime_success = clock_gettime (TIME_UTIL_CLOCK, (p)); \
(void)clock_gettime_success; \
assert (!clock_gettime_success); \
atomic_thread_fence (memory_order_seq_cst); \
} \
while (0)
#define END_TIME(p) \
do \
{ \
struct timespec _end_time_tv; \
atomic_thread_fence (memory_order_seq_cst); \
int clock_gettime_success = clock_gettime (TIME_UTIL_CLOCK, &_end_time_tv); \
(void)clock_gettime_success; \
assert (!clock_gettime_success); \
int timespec_diff_success = timespec_diff ((p), &_end_time_tv, (p)); \
(void)timespec_diff_success; \
assert (!timespec_diff_success); \
atomic_thread_fence (memory_order_seq_cst); \
} \
while (0)
static inline double
get_thread_cpu_time (void)
{
struct timespec _tv;
double _t;
int clock_gettime_success = clock_gettime (CLOCK_THREAD_CPUTIME_ID, &_tv);
(void)clock_gettime_success;
assert (!clock_gettime_success);
_t = _tv.tv_sec;
_t += _tv.tv_nsec * 1e-9;
return _t;
}
static inline int
timespec_diff (struct timespec *_result,
const struct timespec *_px, const struct timespec *_py)
{
struct timespec _x, _y;
_x = *_px;
_y = *_py;
/* Perform the carry for the later subtraction by updating y. */
if (_x.tv_nsec < _y.tv_nsec) {
long _ns = (_y.tv_nsec - _x.tv_nsec) / 1000000000L + 1;
_y.tv_nsec -= 1000000000L * _ns;
_y.tv_sec += _ns;
}
if (_x.tv_nsec - _y.tv_nsec > 1000000000L) {
long _ns = (_x.tv_nsec - _y.tv_nsec) / 1000000000L;
_y.tv_nsec += 1000000000L * _ns;
_y.tv_sec -= _ns;
}
/* Compute the time remaining to wait. tv_nsec is certainly
positive. */
_result->tv_sec = _x.tv_sec - _y.tv_sec;
_result->tv_nsec = _x.tv_nsec - _y.tv_nsec;
/* Return 1 if result is negative. */
return _x.tv_sec < _y.tv_sec;
}
#endif