ttxml: removed cruft from tests
[ccan] / ccan / time / time.c
1 /* Licensed under BSD-MIT - see LICENSE file for details */
2 #include <ccan/time/time.h>
3 #include <stdlib.h>
4 #include <assert.h>
5
6 struct timeval time_now(void)
7 {
8         struct timeval now;
9         gettimeofday(&now, NULL);
10         return now;
11 }
12
13 bool time_greater(struct timeval a, struct timeval b)
14 {
15         if (a.tv_sec > b.tv_sec)
16                 return true;
17         else if (a.tv_sec < b.tv_sec)
18                  return false;
19
20         return a.tv_usec > b.tv_usec;
21 }
22
23 bool time_less(struct timeval a, struct timeval b)
24 {
25         if (a.tv_sec < b.tv_sec)
26                 return true;
27         else if (a.tv_sec > b.tv_sec)
28                  return false;
29
30         return a.tv_usec < b.tv_usec;
31 }
32
33 bool time_eq(struct timeval a, struct timeval b)
34 {
35         return a.tv_sec == b.tv_sec && a.tv_usec == b.tv_usec;
36 }
37
38 struct timeval time_sub(struct timeval recent, struct timeval old)
39 {
40         struct timeval diff;
41
42         diff.tv_sec = recent.tv_sec - old.tv_sec;
43         if (old.tv_usec > recent.tv_usec) {
44                 diff.tv_sec--;
45                 diff.tv_usec = 1000000 + recent.tv_usec - old.tv_usec;
46         } else
47                 diff.tv_usec = recent.tv_usec - old.tv_usec;
48
49         assert(diff.tv_sec >= 0);
50         return diff;
51 }
52
53 struct timeval time_add(struct timeval a, struct timeval b)
54 {
55         struct timeval sum;
56
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) {
60                 sum.tv_sec++;
61                 sum.tv_usec -= 1000000;
62         }
63         return sum;
64 }
65
66 struct timeval time_divide(struct timeval t, unsigned long div)
67 {
68         return time_from_usec(time_to_usec(t) / div);
69 }
70
71 struct timeval time_multiply(struct timeval t, unsigned long mult)
72 {
73         return time_from_usec(time_to_usec(t) * mult);
74 }
75
76 uint64_t time_to_msec(struct timeval t)
77 {
78         uint64_t msec;
79
80         msec = t.tv_usec / 1000 + (uint64_t)t.tv_sec * 1000;
81         return msec;
82 }
83
84 uint64_t time_to_usec(struct timeval t)
85 {
86         uint64_t usec;
87
88         usec = t.tv_usec + (uint64_t)t.tv_sec * 1000000;
89         return usec;
90 }
91
92 struct timeval time_from_msec(uint64_t msec)
93 {
94         struct timeval t;
95
96         t.tv_usec = (msec % 1000) * 1000;
97         t.tv_sec = msec / 1000;
98         return t;
99 }
100
101 struct timeval time_from_usec(uint64_t usec)
102 {
103         struct timeval t;
104
105         t.tv_usec = usec % 1000000;
106         t.tv_sec = usec / 1000000;
107         return t;
108 }