Skip to content

Commit 89a86a9

Browse files
committed
Use mach_absolute_time() on macOS
It would slightly reduce POSIX compatibility overhead on macOS.
1 parent a99d779 commit 89a86a9

1 file changed

Lines changed: 26 additions & 8 deletions

File tree

syscall.c

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,18 @@
55

66
#include "state.h"
77

8+
#if defined(__APPLE__)
9+
#define HAVE_MACH_TIMER
10+
#include <mach/mach_time.h>
11+
#elif !defined(_WIN32) && !defined(_WIN64)
12+
#define HAVE_POSIX_TIMER
13+
#ifdef CLOCK_MONOTONIC
14+
#define CLOCKID CLOCK_MONOTONIC
15+
#else
16+
#define CLOCKID CLOCK_REALTIME
17+
#endif
18+
#endif
19+
820
enum {
921
SYS_getcwd = 17,
1022
SYS_dup = 23,
@@ -142,17 +154,23 @@ static void syscall_gettimeofday(struct riscv_t *rv)
142154

143155
/* return the clock time */
144156
if (tv) {
145-
#if defined(CLOCK_REALTIME) || defined(CLOCK_MONOTONIC)
157+
#if defined(HAVE_POSIX_TIMER)
146158
struct timespec t;
147-
clock_gettime(
148-
#ifdef CLOCK_MONOTONIC
149-
CLOCK_MONOTONIC,
150-
#else
151-
CLOCK_REALTIME,
152-
#endif
153-
&t);
159+
clock_gettime(CLOCKID, &t);
154160
int32_t tv_sec = t.tv_sec;
155161
int32_t tv_usec = t.tv_nsec / 1000;
162+
#elif defined(HAVE_MACH_TIMER)
163+
static mach_timebase_info_data_t info;
164+
/* If this is the first time we have run, get the timebase.
165+
* We can use denom == 0 to indicate that sTimebaseInfo is
166+
* uninitialized.
167+
*/
168+
if (info.denom == 0)
169+
(void) mach_timebase_info(&info);
170+
/* Hope that the multiplication doesn't overflow. */
171+
uint64_t nsecs = mach_absolute_time() * info.numer / info.denom;
172+
int32_t tv_sec = nsecs / 1e9;
173+
int32_t tv_usec = (nsecs / 1e3) - (tv_sec * 1e6);
156174
#else /* low resolution timer */
157175
clock_t t = clock();
158176
int32_t tv_sec = t / CLOCKS_PER_SEC;

0 commit comments

Comments
 (0)