[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()`.
This commit is contained in:
Yakun Xu
2019-05-11 09:57:34 -07:00
committed by Jonathan Hui
parent 5a7faa539f
commit 20a03b4075
2 changed files with 27 additions and 5 deletions
+23 -5
View File
@@ -39,6 +39,7 @@
#include <openthread/platform/diag.h>
#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)
{
+4
View File
@@ -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;
}