]> git.ipfire.org Git - thirdparty/dovecot/core.git/commitdiff
lib: Add i_nanoseconds() and i_microseconds()
authorTimo Sirainen <timo.sirainen@open-xchange.com>
Mon, 3 Feb 2020 10:57:52 +0000 (12:57 +0200)
committeraki.tuomi <aki.tuomi@open-xchange.com>
Thu, 6 Feb 2020 06:46:01 +0000 (06:46 +0000)
src/lib/test-time-util.c
src/lib/time-util.c
src/lib/time-util.h

index b947a20c8b9d52aca96b34e6d7b62a8163942e2c..823f76d88015ada71ae10e7b85abd3789ae36591 100644 (file)
@@ -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();
 }
index 32688c1cd48ea83c8c6fe71771d54ba5e6cdc26c..7e269cd38b0f9f274b50bad5b5dee5bfdfb5aa1b 100644 (file)
@@ -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)
index 139ebf65069f026c6b6ec4508f183a2e2d185053..d8721585276e0a4d1901efb5a508278afdc4e590 100644 (file)
@@ -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 tv1<tv2, 1 if tv1>tv2, 0 if they're equal. */
 int timeval_cmp(const struct timeval *tv1, const struct timeval *tv2);