From 3c0161a3852f7424523c8761c63313ed61b46a41 Mon Sep 17 00:00:00 2001 From: Thomas Haller Date: Tue, 23 Jul 2019 11:40:01 +0200 Subject: [PATCH] shared: add nm_utils_clock_gettime_*() util Using clock_gettime() directly is a bit inconvenient. We usually want to combine the fields of struct timespec into one timestamp (for example, in unit nanoseconds). Add a helper function to do that. --- shared/nm-glib-aux/nm-time-utils.c | 20 ++++++++++++++++++++ shared/nm-glib-aux/nm-time-utils.h | 19 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/shared/nm-glib-aux/nm-time-utils.c b/shared/nm-glib-aux/nm-time-utils.c index 81f88f7c0..4f4c51a96 100644 --- a/shared/nm-glib-aux/nm-time-utils.c +++ b/shared/nm-glib-aux/nm-time-utils.c @@ -273,3 +273,23 @@ nm_utils_monotonic_timestamp_as_boottime (gint64 timestamp, gint64 timestamp_ns_ return timestamp - offset; } + +gint64 +nm_utils_clock_gettime_ns (clockid_t clockid) +{ + struct timespec tp; + + if (clock_gettime (clockid, &tp) != 0) + return -NM_ERRNO_NATIVE (errno); + return nm_utils_timespec_to_ns (&tp); +} + +gint64 +nm_utils_clock_gettime_ms (clockid_t clockid) +{ + struct timespec tp; + + if (clock_gettime (clockid, &tp) != 0) + return -NM_ERRNO_NATIVE (errno); + return nm_utils_timespec_to_ms (&tp); +} diff --git a/shared/nm-glib-aux/nm-time-utils.h b/shared/nm-glib-aux/nm-time-utils.h index 9468cbc98..52d6637dd 100644 --- a/shared/nm-glib-aux/nm-time-utils.h +++ b/shared/nm-glib-aux/nm-time-utils.h @@ -21,6 +21,22 @@ #ifndef __NM_TIME_UTILS_H__ #define __NM_TIME_UTILS_H__ +#include + +static inline gint64 +nm_utils_timespec_to_ns (const struct timespec *ts) +{ + return (((gint64) ts->tv_sec) * ((gint64) NM_UTILS_NS_PER_SECOND)) + + ((gint64) ts->tv_nsec); +} + +static inline gint64 +nm_utils_timespec_to_ms (const struct timespec *ts) +{ + return (((gint64) ts->tv_sec) * ((gint64) 1000)) + + (((gint64) ts->tv_nsec) / ((gint64) NM_UTILS_NS_PER_SECOND / 1000)); +} + gint64 nm_utils_get_monotonic_timestamp_ns (void); gint64 nm_utils_get_monotonic_timestamp_us (void); gint64 nm_utils_get_monotonic_timestamp_ms (void); @@ -34,4 +50,7 @@ nm_utils_get_monotonic_timestamp_ns_cached (gint64 *cache_now) ?: (*cache_now = nm_utils_get_monotonic_timestamp_ns ()); } +gint64 nm_utils_clock_gettime_ns (clockid_t clockid); +gint64 nm_utils_clock_gettime_ms (clockid_t clockid); + #endif /* __NM_TIME_UTILS_H__ */