+int timeval_subtract (struct timeval *result, struct timeval *x,
+ struct timeval *y) {
+ if (x->tv_usec < y->tv_usec) {
+ int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
+ y->tv_usec -= 1000000 * nsec;
+ y->tv_sec += nsec;
+ }
+
+ if (x->tv_usec - y->tv_usec > 1000000) {
+ int nsec = (x->tv_usec - y->tv_usec) / 1000000;
+ y->tv_usec += 1000000 * nsec;
+ y->tv_sec -= nsec;
+ }
+
+ result->tv_sec = x->tv_sec - y->tv_sec;
+ result->tv_usec = x->tv_usec - y->tv_usec;
+
+ return x->tv_sec < y->tv_sec;
+}
+
+double timeval_diff_to_double (struct timeval * x, struct timeval * y) {
+ struct timeval r;
+ timeval_subtract(&r, x, y);
+ return r.tv_sec * 1.0 + r.tv_usec/1000000.0;
+}
+