From 20a03b407563e64519b285ace4d4f3346c7b9199 Mon Sep 17 00:00:00 2001 From: Yakun Xu Date: Sun, 12 May 2019 00:57:34 +0800 Subject: [PATCH] [posix] use monotonic raw timer (#3809) This commit enhances both posix-app and posix simulation to use the clock CLOCK_MONOTONIC_RAW, which is supported on Linux and macOS. However, if this clock is not available, it will fall back to CLOCK_MONOTONIC (for BSD system). On windows, it continues to use `gettimeofday()`. --- examples/platforms/posix/alarm.c | 28 +++++++++++++++++++++++----- src/posix/platform/alarm.c | 4 ++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/examples/platforms/posix/alarm.c b/examples/platforms/posix/alarm.c index ef2ca61d2..ccba28693 100644 --- a/examples/platforms/posix/alarm.c +++ b/examples/platforms/posix/alarm.c @@ -39,6 +39,7 @@ #include #define MS_PER_S 1000 +#define NS_PER_US 1000 #define US_PER_MS 1000 #define US_PER_S 1000000 @@ -52,23 +53,40 @@ static uint32_t sUsAlarm = 0; static uint32_t sSpeedUpFactor = 1; -static struct timeval sStart; - void platformAlarmInit(uint32_t aSpeedUpFactor) { sSpeedUpFactor = aSpeedUpFactor; - gettimeofday(&sStart, NULL); } +#if defined(CLOCK_MONOTONIC_RAW) || defined(CLOCK_MONOTONIC) +uint64_t platformGetNow(void) +{ + struct timespec now; + int err; + +#ifdef CLOCK_MONOTONIC_RAW + err = clock_gettime(CLOCK_MONOTONIC_RAW, &now); +#else + err = clock_gettime(CLOCK_MONOTONIC, &now); +#endif + + assert(err == 0); + + return (uint64_t)now.tv_sec * sSpeedUpFactor * US_PER_S + (uint64_t)now.tv_nsec * sSpeedUpFactor / NS_PER_US; +} +#else uint64_t platformGetNow(void) { struct timeval tv; + int err; - gettimeofday(&tv, NULL); - timersub(&tv, &sStart, &tv); + err = gettimeofday(&tv, NULL); + + assert(err == 0); return (uint64_t)tv.tv_sec * sSpeedUpFactor * US_PER_S + (uint64_t)tv.tv_usec * sSpeedUpFactor; } +#endif // defined(CLOCK_MONOTONIC_RAW) || defined(CLOCK_MONOTONIC) uint32_t otPlatAlarmMilliGetNow(void) { diff --git a/src/posix/platform/alarm.c b/src/posix/platform/alarm.c index 156ce523c..16d9e131c 100644 --- a/src/posix/platform/alarm.c +++ b/src/posix/platform/alarm.c @@ -56,7 +56,11 @@ uint64_t otSysGetTime(void) { struct timespec now; +#ifdef CLOCK_MONOTONIC_RAW + VerifyOrDie(clock_gettime(CLOCK_MONOTONIC_RAW, &now) == 0, OT_EXIT_FAILURE); +#else VerifyOrDie(clock_gettime(CLOCK_MONOTONIC, &now) == 0, OT_EXIT_FAILURE); +#endif return (uint64_t)now.tv_sec * US_PER_S + (uint64_t)now.tv_nsec / NS_PER_US; }