Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-base

Source of release 0.46.0

0.46.0 / src / std / time.lucb

#==============================================================================================
#
#   time - Monotonic and wall-clock time
#
#   DESCRIPTION:
#       A monotonic clock that never goes backwards, and the wall clock as seconds since the
#       Unix epoch, over the host's `clock_gettime`.
#
#==============================================================================================

import c
import platform
extern func clock_gettime(clock: i32, out_time: Stamp*) -> i32
extern func c_time as "time"(out_time: void*?) -> i64

## `struct timespec`: `tv_nsec` is a C `long`, four bytes on Windows.
extern struct Stamp:
    seconds: i64
    nanoseconds: c.long

## `CLOCK_MONOTONIC`: 6 on macOS, 1 on Linux; `CLOCK_REALTIME` is 0 on both.
let monotonic: i32 = 6 if platform.macos else 1
let realtime: i32 = 0

## The clock read into `stamp`: the monotonic one or the wall clock.
func read_clock(monotonic_clock: bool, stamp: Stamp*) -> i32:
    return clock_gettime(monotonic if monotonic_clock else realtime, stamp)

## Nanoseconds from an arbitrary origin, never going backwards.
pub func now() -> u64:
    var stamp = Stamp(seconds = 0, nanoseconds = 0)
    _ = read_clock(true, &stamp)
    return (u64)stamp.seconds * 1000000000 + (u64)stamp.nanoseconds

## Seconds since the Unix epoch.
pub func unix() -> i64:
    return c_time(none)

## Nanoseconds elapsed since `start`, from `now()`.
pub func since(start: u64) -> u64:
    let current = now()
    return current - start if current > start else 0