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