Selaa lähdekoodia

clock_gettime for MacOS

bel 10 vuotta sitten
vanhempi
commit
433c8c75f5
1 muutettua tiedostoa jossa 36 lisäystä ja 8 poistoa
  1. 36 8
      src/civetweb.c

+ 36 - 8
src/civetweb.c

@@ -84,18 +84,46 @@
 
 #ifdef __MACH__
 
-#define CLOCK_REALTIME 0
-#define CLOCK_MONOTONIC 0
+#define CLOCK_MONOTONIC (1)
+#define CLOCK_REALTIME  (2)
 
 #include <sys/time.h>
+#include <mach/clock.h>
+#include <mach/mach.h>
+
 //clock_gettime is not implemented on OSX
 int clock_gettime(int clk_id, struct timespec* t) {
-    struct timeval now;
-    int rv = gettimeofday(&now, NULL);
-    if (rv) return rv;
-    t->tv_sec  = now.tv_sec;
-    t->tv_nsec = now.tv_usec * 1000;
-    return 0;
+
+    if (clk_id == CLOCK_REALTIME) {
+
+        struct timeval now;
+        int rv = gettimeofday(&now, NULL);
+        if (rv) return rv;
+        t->tv_sec  = now.tv_sec;
+        t->tv_nsec = now.tv_usec * 1000;
+        return 0;
+
+    } else if (clk_id == CLOCK_MONOTONIC) {
+
+        static uint64_t start_time = 0;
+        static mach_timebase_info_data_t timebase_ifo = {0};
+
+        uint64_t now = mach_absolute_time();
+
+        if (start_time == 0) {
+            kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
+            assert(mach_status == KERN_SUCCESS);
+            start_time = now;
+        }
+
+        now = (uint64_t)((double)(now - start_time) * (double)timebase_ifo.numer/(double)timebase_ifo.denom);
+
+        t->tv_sec  = now / 1000000000;
+        t->tv_nsec = now % 1000000000;
+        return 0;
+
+    }
+    return -1; /* EINVAL - Clock ID is unknown */
 }
 #endif