[PATCH weston v2 04/11] timespec: Add timespec subtraction helpers

Daniel Stone daniels at collabora.com
Wed Mar 1 11:34:03 UTC 2017


Add helpers to subtract two timespecs, then return the difference in
either milliseconds or nanoseconds. These will be used to compare
timestamps during the repaint cycle.

Signed-off-by: Daniel Stone <daniels at collabora.com>
Suggested-by: Pekka Paalanen <pekka.paalanen at collabora.co.uk>
---
 shared/timespec-util.h | 26 ++++++++++++++++++++++++++
 tests/timespec-test.c  | 22 ++++++++++++++++++++++
 2 files changed, 48 insertions(+)

v2: New in this series. Suggested by Pekka, however the wesgr code was
    not applicable as it normalised to an unsigned range, which is
    inappropriate for our uses. Implemented from scratch.

diff --git a/shared/timespec-util.h b/shared/timespec-util.h
index c8e3cd6..95e0056 100644
--- a/shared/timespec-util.h
+++ b/shared/timespec-util.h
@@ -93,6 +93,20 @@ timespec_to_nsec(const struct timespec *a)
 	return (int64_t)a->tv_sec * NSEC_PER_SEC + a->tv_nsec;
 }
 
+/* Subtract timespecs and return result in nanoseconds
+ *
+ * \param a[in] operand
+ * \param b[in] operand
+ * \return to_nanoseconds(a - b)
+ */
+static inline int64_t
+timespec_sub_to_nsec(const struct timespec *a, const struct timespec *b)
+{
+	struct timespec r;
+	timespec_sub(&r, a, b);
+	return timespec_to_nsec(&r);
+}
+
 /* Convert timespec to milliseconds
  *
  * \param a timespec
@@ -104,6 +118,18 @@ timespec_to_msec(const struct timespec *a)
 	return (int64_t)a->tv_sec * 1000 + a->tv_nsec / 1000000;
 }
 
+/* Subtract timespecs and return result in milliseconds
+ *
+ * \param a[in] operand
+ * \param b[in] operand
+ * \return to_milliseconds(a - b)
+ */
+static inline int64_t
+timespec_sub_to_msec(const struct timespec *a, const struct timespec *b)
+{
+	return timespec_sub_to_nsec(a, b) / 1000000;
+}
+
 /* Convert milli-Hertz to nanoseconds
  *
  * \param mhz frequency in mHz, not zero
diff --git a/tests/timespec-test.c b/tests/timespec-test.c
index 712d1ac..a503911 100644
--- a/tests/timespec-test.c
+++ b/tests/timespec-test.c
@@ -142,3 +142,25 @@ ZUC_TEST(timespec_test, timespec_add_msec)
 	ZUC_ASSERT_EQ(1002, r.tv_sec);
 	ZUC_ASSERT_EQ(2000001, r.tv_nsec);
 }
+
+ZUC_TEST(timespec_test, timespec_sub_to_nsec)
+{
+	struct timespec a, b;
+
+	a.tv_sec = 1000;
+	a.tv_nsec = 1;
+	b.tv_sec = 1;
+	b.tv_nsec = 2;
+	ZUC_ASSERT_EQ((999L * NSEC_PER_SEC) - 1, timespec_sub_to_nsec(&a, &b));
+}
+
+ZUC_TEST(timespec_test, timespec_sub_to_msec)
+{
+	struct timespec a, b;
+
+	a.tv_sec = 1000;
+	a.tv_nsec = 2000000L;
+	b.tv_sec = 2;
+	b.tv_nsec = 1000000L;
+	ZUC_ASSERT_EQ((998 * 1000) + 1, timespec_sub_to_msec(&a, &b));
+}
-- 
2.9.3



More information about the wayland-devel mailing list