Build with:
clang main.c
#include <time.h>
int64_t Timeus () {
const uint64_t tnsec = clock_gettime_nsec_np (CLOCK_UPTIME_RAW);
return tnsec / 1000ull;
}
clock_gettime_nsec_np is a macOS-specific extension to time.h. We use CLOCK_UPTIME_RAW, which is a clock starting from system boot, guaranteed to never go backward between calls. We get back the time in nanoseconds, which we convert to microseconds - plenty of precision for games.
You may find macOS example code using mach_absolute_time(). The official Apple documentation of this function states: "Prefer to use the equivalent clock_gettime_nsec_np(CLOCK_UPTIME_RAW)". Before I read that note, I was using mach_absolute_time. Then my friend ran NSMG on their m2 macbook, running macOS 13, and had crazy timing bugs. These were entirely resolved by switching to clock_gettime_nsec_np (CLOCK_UPTIME_RAW).