Skip to content

Instantly share code, notes, and snippets.

@lisdude
Last active November 18, 2022 05:27
Show Gist options
  • Save lisdude/b8f7d6ee3fc48788ba83e6b1691d7566 to your computer and use it in GitHub Desktop.
Save lisdude/b8f7d6ee3fc48788ba83e6b1691d7566 to your computer and use it in GitHub Desktop.
A MOO-like ftime() function for Genesis.
COLDC_FUNC(ftime) {
cData *args;
Int num_args;
/* Take an optional integer argument indicating whether we use monotonic time or not. */
if (!func_init_0_or_1(&args, &num_args, INTEGER))
return;
#ifdef __MACH__
// macOS only provides SYSTEM_CLOCK for monotonic time, so our arguments don't matter.
clock_id_t clock_type = (num_args == 0 ? CALENDAR_CLOCK : SYSTEM_CLOCK);
#else
// Other OSes provide MONOTONIC_RAW and MONOTONIC, so we'll check args for 2(raw) or 1.
clockid_t clock_type = 0;
if (num_args == 0)
clock_type = CLOCK_REALTIME;
else
#if defined(__WIN32) || defined(__CYGWIN__)
// CYGWIN doesn't give us MONOTONIC_RAW
clock_type = CLOCK_MONOTONIC;
#else
clock_type = args[0].u.val == 2 ? CLOCK_MONOTONIC_RAW : CLOCK_MONOTONIC;
#endif
#endif
struct timespec ts;
#ifdef __MACH__
// macOS lacks clock_gettime, use clock_get_time instead
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), clock_type, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts.tv_sec = mts.tv_sec;
ts.tv_nsec = mts.tv_nsec;
#else
clock_gettime(clock_type, &ts);
#endif
Float r = (Float)ts.tv_sec + (Float)ts.tv_nsec * 1e-9;
push_float(r);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment