Skip to content

Commit c411229

Browse files
committed
time: cross-platform timespec_get
1 parent 3e91668 commit c411229

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

src/time/time.c

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@
1313
#include <time.h>
1414
#include "time/timex.h"
1515

16+
// Some older systems do not support timespec_get() from time.h
17+
#if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 201112L || \
18+
(!defined(TIME_UTC) && (!defined(_POSIX_TIMERS) || _POSIX_TIMERS <= 0))
19+
#include <sys/time.h>
20+
#endif
21+
1622
#pragma region Private
1723

1824
static const int64_t seconds_per_minute = 60;
@@ -246,14 +252,29 @@ static Duration time_div(Time t, Duration d) {
246252
return r;
247253
}
248254

255+
// timespec_now returns the current time with nanosecond precision.
256+
static struct timespec timespec_now(void) {
257+
struct timespec ts;
258+
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && defined(TIME_UTC)
259+
timespec_get(&ts, TIME_UTC);
260+
#elif defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0)
261+
clock_gettime(CLOCK_REALTIME, &ts);
262+
#else
263+
struct timeval tv;
264+
gettimeofday(&tv, NULL);
265+
ts.tv_sec = tv.tv_sec;
266+
ts.tv_nsec = tv.tv_usec * 1000;
267+
#endif
268+
return ts;
269+
}
270+
249271
#pragma endregion
250272

251273
#pragma region Constructors
252274

253275
// time_now returns the current time in UTC.
254276
Time time_now(void) {
255-
struct timespec ts;
256-
timespec_get(&ts, TIME_UTC);
277+
struct timespec ts = timespec_now();
257278
return unix_time(ts.tv_sec, ts.tv_nsec);
258279
}
259280

0 commit comments

Comments
 (0)