Skip to content

Commit

Permalink
utilities.c: Add utility function iio_read_counter_us()
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
pcercuei committed Jul 10, 2023
1 parent 879e49b commit 209163a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions iio-private.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
28 changes: 28 additions & 0 deletions utilities.c
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@
#include <stdlib.h>
#include <string.h>

#ifdef _WIN32
#include <Windows.h>
#else
#include <time.h>
#endif

#if defined(_WIN32) || \
(defined(__APPLE__) && defined(__MACH__)) || \
(defined(__USE_XOPEN2K8) && \
Expand Down Expand Up @@ -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;
}

0 comments on commit 209163a

Please sign in to comment.