1 /* Licensed under BSD-MIT - see LICENSE file for details */
2 #include <ccan/time/time.h>
6 struct timeval
time_now(void)
9 gettimeofday(&now
, NULL
);
13 bool time_greater(struct timeval a
, struct timeval b
)
15 if (a
.tv_sec
> b
.tv_sec
)
17 else if (a
.tv_sec
< b
.tv_sec
)
20 return a
.tv_usec
> b
.tv_usec
;
23 bool time_less(struct timeval a
, struct timeval b
)
25 if (a
.tv_sec
< b
.tv_sec
)
27 else if (a
.tv_sec
> b
.tv_sec
)
30 return a
.tv_usec
< b
.tv_usec
;
33 bool time_eq(struct timeval a
, struct timeval b
)
35 return a
.tv_sec
== b
.tv_sec
&& a
.tv_usec
== b
.tv_usec
;
38 struct timeval
time_sub(struct timeval recent
, struct timeval old
)
42 diff
.tv_sec
= recent
.tv_sec
- old
.tv_sec
;
43 if (old
.tv_usec
> recent
.tv_usec
) {
45 diff
.tv_usec
= 1000000 + recent
.tv_usec
- old
.tv_usec
;
47 diff
.tv_usec
= recent
.tv_usec
- old
.tv_usec
;
49 assert(diff
.tv_sec
>= 0);
53 struct timeval
time_add(struct timeval a
, struct timeval b
)
57 sum
.tv_sec
= a
.tv_sec
+ b
.tv_sec
;
58 sum
.tv_usec
= a
.tv_usec
+ b
.tv_usec
;
59 if (sum
.tv_usec
> 1000000) {
61 sum
.tv_usec
-= 1000000;
66 struct timeval
time_divide(struct timeval t
, unsigned long div
)
68 return time_from_usec(time_to_usec(t
) / div
);
71 struct timeval
time_multiply(struct timeval t
, unsigned long mult
)
73 return time_from_usec(time_to_usec(t
) * mult
);
76 uint64_t time_to_msec(struct timeval t
)
80 msec
= t
.tv_usec
/ 1000 + (uint64_t)t
.tv_sec
* 1000;
84 uint64_t time_to_usec(struct timeval t
)
88 usec
= t
.tv_usec
+ (uint64_t)t
.tv_sec
* 1000000;
92 struct timeval
time_from_msec(uint64_t msec
)
96 t
.tv_usec
= (msec
% 1000) * 1000;
97 t
.tv_sec
= msec
/ 1000;
101 struct timeval
time_from_usec(uint64_t usec
)
105 t
.tv_usec
= usec
% 1000000;
106 t
.tv_sec
= usec
/ 1000000;