308711e5 |
1 | #ifndef LTT_TIME_H |
2 | #define LTT_TIME_H |
3 | |
4 | |
5 | typedef struct _LttTime { |
6 | unsigned long tv_sec; |
7 | unsigned long tv_nsec; |
8 | } LttTime; |
9 | |
10 | |
11 | static const unsigned long NANOSECONDS_PER_SECOND = 1000000000; |
12 | |
13 | static const LttTime ltt_time_zero = { 0, 0}; |
14 | |
15 | |
16 | static inline LttTime ltt_time_sub(LttTime t1, LttTime t2) |
17 | { |
18 | LttTime res; |
19 | res.tv_sec = t1.tv_sec - t2.tv_sec; |
20 | if(t1.tv_nsec < t2.tv_nsec) { |
21 | res.tv_sec--; |
22 | res.tv_nsec = NANOSECONDS_PER_SECOND + t1.tv_nsec - t2.tv_nsec; |
23 | } |
24 | else { |
25 | res.tv_nsec = t1.tv_nsec - t2.tv_nsec; |
26 | } |
27 | return res; |
28 | } |
29 | |
30 | |
31 | static inline LttTime ltt_time_add(LttTime t1, LttTime t2) |
32 | { |
33 | LttTime res; |
34 | res.tv_sec = t1.tv_sec + t2.tv_sec; |
35 | res.tv_nsec = t1.tv_nsec + t2.tv_nsec; |
36 | if(res.tv_nsec >= NANOSECONDS_PER_SECOND) { |
37 | res.tv_sec++; |
38 | res.tv_nsec -= NANOSECONDS_PER_SECOND; |
39 | } |
40 | return res; |
41 | } |
42 | |
43 | |
44 | static inline LttTime ltt_time_mul(LttTime t1, float f) |
45 | { |
308711e5 |
46 | LttTime res; |
1f1ae829 |
47 | float d = 1.0/f; |
48 | double sec; |
308711e5 |
49 | |
1f1ae829 |
50 | if(f == 0.0){ |
51 | res.tv_sec = 0; |
52 | res.tv_nsec = 0; |
53 | }else{ |
54 | sec = t1.tv_sec / (double)d; |
55 | res.tv_sec = sec; |
56 | res.tv_nsec = t1.tv_nsec / (double)d + (sec - res.tv_sec) * |
57 | NANOSECONDS_PER_SECOND; |
58 | res.tv_sec += res.tv_nsec / NANOSECONDS_PER_SECOND; |
59 | res.tv_nsec %= NANOSECONDS_PER_SECOND; |
60 | } |
308711e5 |
61 | return res; |
62 | } |
63 | |
64 | |
65 | static inline LttTime ltt_time_div(LttTime t1, float f) |
66 | { |
67 | double sec; |
68 | LttTime res; |
69 | |
70 | sec = t1.tv_sec / (double)f; |
71 | res.tv_sec = sec; |
72 | res.tv_nsec = t1.tv_nsec / (double)f + (sec - res.tv_sec) * |
73 | NANOSECONDS_PER_SECOND; |
1f1ae829 |
74 | res.tv_sec += res.tv_nsec / NANOSECONDS_PER_SECOND; |
75 | res.tv_nsec %= NANOSECONDS_PER_SECOND; |
308711e5 |
76 | return res; |
77 | } |
78 | |
79 | |
80 | static inline int ltt_time_compare(LttTime t1, LttTime t2) |
81 | { |
82 | if(t1.tv_sec > t2.tv_sec) return 1; |
83 | if(t1.tv_sec < t2.tv_sec) return -1; |
84 | if(t1.tv_nsec > t2.tv_nsec) return 1; |
85 | if(t1.tv_nsec < t2.tv_nsec) return -1; |
86 | return 0; |
87 | } |
88 | |
89 | |
90 | static inline double ltt_time_to_double(LttTime t1) |
91 | { |
92 | return (double)t1.tv_sec + (double)t1.tv_nsec / NANOSECONDS_PER_SECOND; |
93 | } |
94 | |
95 | |
96 | static inline LttTime ltt_time_from_double(double t1) |
97 | { |
98 | LttTime res; |
99 | res.tv_sec = t1; |
100 | res.tv_nsec = (t1 - res.tv_sec) * NANOSECONDS_PER_SECOND; |
101 | return res; |
102 | } |
103 | |
104 | #endif // LTT_TIME_H |