From 209163ae9ca4d23a8078c179b2dd1971d4e6f878 Mon Sep 17 00:00:00 2001 From: Paul Cercueil Date: Wed, 23 Nov 2022 12:23:32 +0000 Subject: [PATCH] utilities.c: Add utility function iio_read_counter_us() This function can be used to get the value of a counter with a precision of a microsecond. The value returned is not properly defined, and as such does not allow to represent a specific point in time, but allows to compute periods and delays. Signed-off-by: Paul Cercueil --- iio-private.h | 1 + utilities.c | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/iio-private.h b/iio-private.h index 9cc50a5c5..3435798cc 100644 --- a/iio-private.h +++ b/iio-private.h @@ -264,6 +264,7 @@ char *iio_strndup(const char *str, size_t n); char *iio_strtok_r(char *str, const char *delim, char **saveptr); size_t iio_strlcpy(char * __restrict dst, const char * __restrict src, size_t dsize); char * iio_getenv (char * envvar); +uint64_t iio_read_counter_us(void); int iio_context_add_device(struct iio_context *ctx, struct iio_device *dev); diff --git a/utilities.c b/utilities.c index 5dc26887f..92e29af7f 100644 --- a/utilities.c +++ b/utilities.c @@ -20,6 +20,12 @@ #include #include +#ifdef _WIN32 +#include +#else +#include +#endif + #if defined(_WIN32) || \ (defined(__APPLE__) && defined(__MACH__)) || \ (defined(__USE_XOPEN2K8) && \ @@ -359,3 +365,25 @@ ssize_t __iio_printf iio_snprintf(char *buf, size_t len, const char *fmt, ...) return (ssize_t)ret; } + +uint64_t iio_read_counter_us(void) +{ + uint64_t value; + +#ifdef _WIN32 + LARGE_INTEGER freq, cnt; + + QueryPerformanceFrequency(&freq); + QueryPerformanceCounter(&cnt); + + value = (1000000 * cnt.QuadPart) / freq.QuadPart; +#else + struct timespec ts; + + clock_gettime(CLOCK_MONOTONIC, &ts); + + value = ts.tv_sec * 1000000ull + (uint64_t)ts.tv_nsec / 1000ull; +#endif + + return value; +}