aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMike Perry <mikeperry-git@fscked.org>2009-09-20 18:03:39 -0700
committerMike Perry <mikeperry-git@fscked.org>2009-09-20 18:03:39 -0700
commite2cc4e353a73595aebd13ba89cc8b057a6242b27 (patch)
treea78db94a3b89d488e4e30e00010d004f60f28b60
parentcf2afcd7072d20755ad030ed8240c21ec649dcd7 (diff)
downloadtor-e2cc4e353a73595aebd13ba89cc8b057a6242b27.tar
tor-e2cc4e353a73595aebd13ba89cc8b057a6242b27.tar.gz
Add a couple of time helper functions.
Also add rounding support to tv_mdiff().
-rw-r--r--src/common/util.c40
-rw-r--r--src/common/util.h3
2 files changed, 42 insertions, 1 deletions
diff --git a/src/common/util.c b/src/common/util.c
index e4e073d99..a69ea33d0 100644
--- a/src/common/util.c
+++ b/src/common/util.c
@@ -1034,6 +1034,42 @@ wrap_string(smartlist_t *out, const char *string, size_t width,
* Time
* ===== */
+/**
+ * Converts struct timeval to a double value.
+ * Preserves microsecond precision, but just barely.
+ * Error is approx +/- 0.1 usec when dealing with epoch values.
+ */
+double
+tv_to_double(const struct timeval *tv)
+{
+ double conv = tv->tv_sec;
+ conv += tv->tv_usec/1000000.0;
+ return conv;
+}
+
+/**
+ * Converts timeval to milliseconds.
+ */
+int64_t
+tv_to_msec(const struct timeval *tv)
+{
+ int64_t conv = ((int64_t)tv->tv_sec)*1000L;
+ /* Round ghetto-style */
+ conv += (tv->tv_usec+500)/1000L;
+ return conv;
+}
+
+/**
+ * Converts timeval to microseconds.
+ */
+int64_t
+tv_to_usec(const struct timeval *tv)
+{
+ int64_t conv = ((int64_t)tv->tv_sec)*1000000L;
+ conv += tv->tv_usec;
+ return conv;
+}
+
/** Return the number of microseconds elapsed between *start and *end.
*/
long
@@ -1066,7 +1102,9 @@ tv_mdiff(const struct timeval *start, const struct timeval *end)
return LONG_MAX;
}
- mdiff = secdiff*1000L + ((long)end->tv_usec - (long)start->tv_usec) / 1000L;
+ /* Subtract and round */
+ mdiff = secdiff*1000L +
+ ((long)end->tv_usec - (long)start->tv_usec + 500L) / 1000L;
return mdiff;
}
diff --git a/src/common/util.h b/src/common/util.h
index bb384a2a3..28ea8a048 100644
--- a/src/common/util.h
+++ b/src/common/util.h
@@ -212,6 +212,9 @@ void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen);
int base16_decode(char *dest, size_t destlen, const char *src, size_t srclen);
/* Time helpers */
+double tv_to_double(const struct timeval *tv);
+int64_t tv_to_msec(const struct timeval *tv);
+int64_t tv_to_usec(const struct timeval *tv);
long tv_udiff(const struct timeval *start, const struct timeval *end);
long tv_mdiff(const struct timeval *start, const struct timeval *end);
time_t tor_timegm(struct tm *tm);