From 93f316d2c672378bc9eb1be636111c6e4a2810a0 Mon Sep 17 00:00:00 2001 From: Matteo Cypriani Date: Fri, 6 Jan 2012 13:45:47 +0100 Subject: [PATCH] [lib] Fix time_elapsed() The previous implementation was very naive and incorrect. --- libowlps/libowlps.c | 59 +++++++++++++++++++++++++++++++++++++++------ libowlps/owlps.h | 5 ++-- 2 files changed, 54 insertions(+), 10 deletions(-) diff --git a/libowlps/libowlps.c b/libowlps/libowlps.c index d2300a5..79a1835 100644 --- a/libowlps/libowlps.c +++ b/libowlps/libowlps.c @@ -250,20 +250,63 @@ void owl_timestamp_to_string(char *const dst, const owl_timestamp src) uint_fast32_t owl_time_elapsed_ms(const owl_timestamp d1, const owl_timestamp d2) { - return owl_timestamp_to_ms(owl_time_elapsed(d1, d2)) ; + owl_timestamp elapsed ; + owl_time_elapsed(&d1, &d2, &elapsed) ; + return owl_timestamp_to_ms(elapsed) ; } /* - * Returns a owl_timestamp storing the time between two dates. + * Computes the time difference between two owl_timestamp 'd1' and + * 'd2'. + * Note that it is a delay, not a simple substraction, therefore the + * result is always positive. The result is stored in the 'elapsed' + * argument. */ -owl_timestamp owl_time_elapsed(const owl_timestamp d1, - const owl_timestamp d2) +void owl_time_elapsed(const owl_timestamp *const d1, + const owl_timestamp *const d2, + owl_timestamp *const elapsed) { - owl_timestamp elapsed ; - elapsed.tv_sec = abs(d1.tv_sec - d2.tv_sec) ; - elapsed.tv_nsec = abs(d1.tv_nsec - d2.tv_nsec) ; - return elapsed ; + int_fast32_t sec, nsec ; + + assert(d1) ; + assert(d2) ; + assert(elapsed) ; + + sec = (int_fast64_t) d1->tv_sec - d2->tv_sec ; + nsec = (int_fast64_t) d1->tv_nsec - d2->tv_nsec ; + + if (sec == 0) + { + elapsed->tv_sec = 0 ; + elapsed->tv_nsec = abs(nsec) ; + } + else if (sec > 0) + { + if (nsec >= 0) + { + elapsed->tv_sec = sec ; + elapsed->tv_nsec = nsec ; + } + else // nsec < 0 + { + elapsed->tv_sec = sec - 1 ; + elapsed->tv_nsec = nsec + 1000000000ul ; + } + } + else // sec < 0 + { + if (nsec > 0) + { + elapsed->tv_sec = abs(sec) - 1 ; + elapsed->tv_nsec = 1000000000ul - nsec ; + } + else // nsec <= 0 + { + elapsed->tv_sec = abs(sec) ; + elapsed->tv_nsec = abs(nsec) ; + } + } } diff --git a/libowlps/owlps.h b/libowlps/owlps.h index 972a43d..71b7fe4 100644 --- a/libowlps/owlps.h +++ b/libowlps/owlps.h @@ -221,8 +221,9 @@ uint64_t owl_timestamp_to_ms(const owl_timestamp d) ; void owl_timestamp_to_string(char *const dst, const owl_timestamp src) ; uint_fast32_t owl_time_elapsed_ms(const owl_timestamp d1, const owl_timestamp d2) ; -owl_timestamp owl_time_elapsed(const owl_timestamp d1, - const owl_timestamp d2) ; +void owl_time_elapsed(const owl_timestamp *const d1, + const owl_timestamp *const d2, + owl_timestamp *const elapsed) ; // Endianess owl_timestamp owl_hton_timestamp(const owl_timestamp d) ;