X-Git-Url: https://git.sesse.net/?a=blobdiff_plain;f=timeutil.cpp;fp=timeutil.cpp;h=b3d58a7c8fd6f8369e920d9023bbb8a2e558a8d2;hb=2ea5c13b47daf62bccdcaa2cb6f971383df54ad7;hp=0000000000000000000000000000000000000000;hpb=45fc511092347489c5cb6ed76cd5fba593b93fa6;p=greproxy diff --git a/timeutil.cpp b/timeutil.cpp new file mode 100644 index 0000000..b3d58a7 --- /dev/null +++ b/timeutil.cpp @@ -0,0 +1,48 @@ +#include + +#include + +#include "timeutil.h" + +using namespace std; + +double tdiff(const timeval& a, const timeval& b) +{ + return b.tv_sec - a.tv_sec + + 1e-6 * (b.tv_usec - a.tv_usec); +} + +bool less_than(const timeval &a, const timeval &b) +{ + return make_pair(a.tv_sec, a.tv_usec) < make_pair(b.tv_sec, b.tv_usec); +} + +timeval subtract_timeval_saturate(const timeval &a, const timeval &b) +{ + timeval ret; + if (less_than(a, b)) { + ret.tv_sec = ret.tv_usec = 0; + return ret; + } + ret.tv_sec = b.tv_sec - a.tv_sec; + ret.tv_usec = b.tv_usec - a.tv_usec; + if (ret.tv_usec < 0) { + ret.tv_usec += 1000000; + --ret.tv_sec; + } + return ret; +} + +timeval offset_timeval_seconds(const timeval &a, double s) +{ + int usec_to_add = lrint(1e6 * s); + int sec_to_add = usec_to_add / 1000000; + usec_to_add %= 1000000; + + timeval ret = a; + ret.tv_usec += usec_to_add; + ret.tv_sec += sec_to_add; + ret.tv_sec += ret.tv_usec / 1000000; + ret.tv_usec %= 1000000; + return ret; +}