Skip to content

ClockMonoNs

Description

Current value of the monotonic clock, in nanoseconds.

The epoch is unspecified (boot-relative on Linux, an arbitrary fixed origin elsewhere); only the difference between two readings is meaningful. Resolution is the platform clock’s native granularity – nanoseconds on Linux/Darwin, the QueryPerformanceFrequency tick on Windows scaled to ns.

Thread-safety: safe to call concurrently; reads a kernel/commpage time source and keeps no shared state of its own.

Success

Returns a monotonically non-decreasing nanosecond count.

Failure

Aborts via LOG_FATAL if the platform clock query fails (a non-functional monotonic clock is treated as a fatal system condition, the same fail-fast contract as Prng64; there is no safe fallback value to return).

Usage example (Cross-references)

Usage examples (Cross-references)
    } clock_timespec;
    
    u64 ClockMonoNs(void) {
    #if PLATFORM_WINDOWS
        LARGE_INTEGER counter;
        LARGE_INTEGER freq;
        if (!QueryPerformanceCounter(&counter) || !QueryPerformanceFrequency(&freq) || freq.QuadPart <= 0)
            LOG_FATAL("ClockMonoNs: QueryPerformanceCounter/Frequency failed");
        u64 ticks = (u64)counter.QuadPart;
        u64 hz    = (u64)freq.QuadPart;
        clock_timespec ts;
        if (!clock_gettime || clock_gettime(CLOCK_MONOTONIC_RAW_ID, &ts) != 0)
            LOG_FATAL("ClockMonoNs: clock_gettime failed");
        return (u64)ts.tv_sec * 1000000000ull + (u64)ts.tv_nsec;
    #elif FEATURE_DIRECT_SYSCALL
        long           ret = direct_sys2(MISRA_SYS_clock_gettime, (long)CLOCK_MONOTONIC_RAW_ID, (long)(u64)&ts);
        if (ret < 0)
            LOG_FATAL("ClockMonoNs: clock_gettime syscall failed");
        return (u64)ts.tv_sec * 1000000000ull + (u64)ts.tv_nsec;
    #else
        clock_timespec ts;
        if (!clock_gettime || clock_gettime(1, &ts) != 0)
            LOG_FATAL("ClockMonoNs: clock_gettime unavailable");
        return (u64)ts.tv_sec * 1000000000ull + (u64)ts.tv_nsec;
    #endif
Last updated on