From: Timo Sirainen Date: Mon, 3 Feb 2020 10:57:52 +0000 (+0200) Subject: lib: Add i_nanoseconds() and i_microseconds() X-Git-Tag: 2.3.10~96 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=2666cfb8d5d234d73f3c24df477544c685524ab7;p=thirdparty%2Fdovecot%2Fcore.git lib: Add i_nanoseconds() and i_microseconds() --- diff --git a/src/lib/test-time-util.c b/src/lib/test-time-util.c index b947a20c8b..823f76d880 100644 --- a/src/lib/test-time-util.c +++ b/src/lib/test-time-util.c @@ -335,6 +335,25 @@ static void test_strftime_fixed(void) test_end(); } +static void test_micro_nanoseconds(void) +{ + uint64_t secs, usecs, nsecs; + + test_begin("i_microseconds() and i_nanoseconds()"); + + secs = time(NULL); + usecs = i_microseconds(); + nsecs = i_nanoseconds(); + + /* Assume max 1 seconds time difference between the calls. That should + be more than enough, while still not failing if there are temporary + hangs when running in heavily loaded systems. */ + test_assert(usecs/1000000 - secs <= 1); + test_assert(nsecs/1000 - usecs <= 1000000); + + test_end(); +} + void test_time_util(void) { test_timeval_cmp(); @@ -343,4 +362,5 @@ void test_time_util(void) test_time_to_local_day_start(); test_strftime_now(); test_strftime_fixed(); + test_micro_nanoseconds(); } diff --git a/src/lib/time-util.c b/src/lib/time-util.c index 32688c1cd4..7e269cd38b 100644 --- a/src/lib/time-util.c +++ b/src/lib/time-util.c @@ -13,6 +13,15 @@ void i_gettimeofday(struct timeval *tv_r) i_fatal("gettimeofday() failed: %m"); } +uint64_t i_nanoseconds(void) +{ + struct timespec ts; + + if (clock_gettime(CLOCK_REALTIME, &ts) < 0) + i_fatal("clock_gettime() failed: %m"); + return ts.tv_sec * 1000000000ULL + ts.tv_nsec; +} + int timeval_cmp(const struct timeval *tv1, const struct timeval *tv2) { if (tv1->tv_sec < tv2->tv_sec) diff --git a/src/lib/time-util.h b/src/lib/time-util.h index 139ebf6506..d872158527 100644 --- a/src/lib/time-util.h +++ b/src/lib/time-util.h @@ -5,6 +5,12 @@ /* Same as gettimeofday(), but call i_fatal() if the call fails. */ void i_gettimeofday(struct timeval *tv_r); +/* Return nanoseconds since UNIX epoch (1970-01-01). */ +uint64_t i_nanoseconds(void); +/* Return microseconds since UNIX epoch (1970-01-01). */ +static inline uint64_t i_microseconds(void) { + return i_nanoseconds() / 1000; +} /* Returns -1 if tv1tv2, 0 if they're equal. */ int timeval_cmp(const struct timeval *tv1, const struct timeval *tv2);