gettime: Introduce rel_time_since()
authorBart Van Assche <bvanassche@acm.org>
Fri, 4 Sep 2020 23:18:53 +0000 (16:18 -0700)
committerBart Van Assche <bvanassche@acm.org>
Sun, 20 Sep 2020 23:09:45 +0000 (16:09 -0700)
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 <bvanassche@acm.org>
fio_time.h
gettime.c

index c00f8e7866d94fd47ae6e0b54f03453efdbd0844..b3bbd4c011c2518aea5cbf5523f514136f8601b3 100644 (file)
@@ -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 *);
index fcb536d079160eadf6b896bf6e31438f5bf8d171..f85da6e082c8d7cef315f644a2be90cf853ce82f 100644 (file)
--- 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)