]> git.sesse.net Git - greproxy/blob - timeutil.cpp
Merge branch 'master' of morgental.zrh.sesse.net:greproxy
[greproxy] / timeutil.cpp
1 #include <sys/time.h>
2
3 #include <algorithm>
4
5 #include "timeutil.h"
6
7 using namespace std;
8
9 double tdiff(const timeval& a, const timeval& b)
10 {
11         return b.tv_sec - a.tv_sec +
12                 1e-6 * (b.tv_usec - a.tv_usec);
13 }
14
15 bool less_than(const timeval &a, const timeval &b)
16 {
17         return make_pair(a.tv_sec, a.tv_usec) < make_pair(b.tv_sec, b.tv_usec);
18 }
19
20 timeval subtract_timeval_saturate(const timeval &b, const timeval &a)
21 {       
22         timeval ret;
23         if (less_than(b, a)) {
24                 ret.tv_sec = ret.tv_usec = 0;
25                 return ret;
26         }
27         ret.tv_sec = b.tv_sec - a.tv_sec;
28         ret.tv_usec = b.tv_usec - a.tv_usec;
29         if (ret.tv_usec < 0) {
30                 ret.tv_usec += 1000000;
31                 --ret.tv_sec;
32         }
33         return ret;
34 }
35
36 timeval offset_timeval_seconds(const timeval &a, double s)
37 {
38         int usec_to_add = lrint(1e6 * s);
39         int sec_to_add = usec_to_add / 1000000;
40         usec_to_add %= 1000000;
41
42         timeval ret = a;
43         ret.tv_usec += usec_to_add;
44         ret.tv_sec += sec_to_add;
45         ret.tv_sec += ret.tv_usec / 1000000;
46         ret.tv_usec %= 1000000;
47         return ret;
48 }