From 383c796046c2263b89d8115f1fa696ce3e7d5adc Mon Sep 17 00:00:00 2001 From: Bart Van Assche Date: Fri, 4 Sep 2020 16:18:53 -0700 Subject: [PATCH] gettime: Introduce rel_time_since() rel_time_since() subtracts two timespecs and returns the result as a signed integer. Instead of using the implementation from mtime_since(), use an implementation that only performs one division instead of two. Signed-off-by: Bart Van Assche --- fio_time.h | 2 ++ gettime.c | 30 ++++++++++++++++++++---------- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/fio_time.h b/fio_time.h index c00f8e78..b3bbd4c0 100644 --- a/fio_time.h +++ b/fio_time.h @@ -13,6 +13,8 @@ extern uint64_t ntime_since(const struct timespec *, const struct timespec *); extern uint64_t ntime_since_now(const struct timespec *); extern uint64_t utime_since(const struct timespec *, const struct timespec *); extern uint64_t utime_since_now(const struct timespec *); +extern int64_t rel_time_since(const struct timespec *, + const struct timespec *); extern uint64_t mtime_since(const struct timespec *, const struct timespec *); extern uint64_t mtime_since_now(const struct timespec *); extern uint64_t mtime_since_tv(const struct timeval *, const struct timeval *); diff --git a/gettime.c b/gettime.c index fcb536d0..f85da6e0 100644 --- a/gettime.c +++ b/gettime.c @@ -524,23 +524,33 @@ uint64_t mtime_since_now(const struct timespec *s) return mtime_since(s, &t); } -uint64_t mtime_since(const struct timespec *s, const struct timespec *e) +/* + * Returns *e - *s in milliseconds as a signed integer. Note: rounding is + * asymmetric. If the difference yields +1 ns then 0 is returned. If the + * difference yields -1 ns then -1 is returned. + */ +int64_t rel_time_since(const struct timespec *s, const struct timespec *e) { - int64_t sec, usec; + int64_t sec, nsec; sec = e->tv_sec - s->tv_sec; - usec = (e->tv_nsec - s->tv_nsec) / 1000; - if (sec > 0 && usec < 0) { + nsec = e->tv_nsec - s->tv_nsec; + if (nsec < 0) { sec--; - usec += 1000000; + nsec += 1000ULL * 1000 * 1000; } + assert(0 <= nsec && nsec < 1000ULL * 1000 * 1000); - if (sec < 0 || (sec == 0 && usec < 0)) - return 0; + return sec * 1000 + nsec / (1000 * 1000); +} - sec *= 1000; - usec /= 1000; - return sec + usec; +/* + * Returns *e - *s in milliseconds as an unsigned integer. Returns 0 if + * *e < *s. + */ +uint64_t mtime_since(const struct timespec *s, const struct timespec *e) +{ + return max(rel_time_since(s, e), (int64_t)0); } uint64_t time_since_now(const struct timespec *s) -- 2.25.1