浏览代码

express: Use monotonic clock on POSIX (has nanosecond precision)

rdb 10 月之前
父节点
当前提交
da4e2cad9f
共有 1 个文件被更改,包括 17 次插入18 次删除
  1. 17 18
      panda/src/express/trueClock.cxx

+ 17 - 18
panda/src/express/trueClock.cxx

@@ -521,6 +521,7 @@ TrueClock() {
 #include <stdio.h>  // for perror
 
 static long _init_sec;
+static time_t _init_sec_monotonic = 0;
 
 /**
  *
@@ -553,25 +554,13 @@ get_long_time() {
  */
 double TrueClock::
 get_short_raw_time() {
-  struct timeval tv;
-
-  int result;
-
-#ifdef GETTIMEOFDAY_ONE_PARAM
-  result = gettimeofday(&tv);
-#else
-  result = gettimeofday(&tv, nullptr);
-#endif
-
-  if (result < 0) {
-    // Error in gettimeofday().
-    return 0.0;
+#if defined(CLOCK_MONOTONIC) && !defined(__APPLE__)
+  struct timespec spec;
+  if (clock_gettime(CLOCK_MONOTONIC, &spec) == 0) {
+    return (double)(spec.tv_sec - _init_sec_monotonic) + (double)spec.tv_nsec / 1000000000.0;
   }
-
-  // We subtract out the time at which the clock was initialized, because we
-  // don't care about the number of seconds all the way back to 1970, and we
-  // want to leave the double with as much precision as it can get.
-  return (double)(tv.tv_sec - _init_sec) + (double)tv.tv_usec / 1000000.0;
+#endif
+  return get_long_time();
 }
 
 /**
@@ -603,6 +592,16 @@ TrueClock() {
   } else {
     _init_sec = tv.tv_sec;
   }
+
+#if defined(CLOCK_MONOTONIC) && !defined(__APPLE__)
+  struct timespec spec;
+  if (clock_gettime(CLOCK_MONOTONIC, &spec) == 0) {
+    _init_sec_monotonic = spec.tv_sec;
+  } else {
+    perror("clock_gettime(CLOCK_MONOTONIC)");
+    _init_sec_monotonic = 0;
+  }
+#endif
 }
 
 #endif