Nyx by Example

Sleep and Timers

time_ms() returns the current wall-clock time in milliseconds as an int. Subtracting two readings gives an elapsed duration. sleep(ms) suspends the current thread for the specified number of milliseconds.

Code

// Timer y sleep: medir tiempo transcurrido con time_ms() y pausar con sleep()

fn main() -> int {
    print("start")

    let t0: int = time_ms()

    // Pausar 500 milisegundos
    sleep(500)

    let t1: int = time_ms()
    let elapsed: int = t1 - t0

    print("500ms passed")
    print("tiempo real: " + int_to_string(elapsed) + "ms")

    // Medir una operacion costosa
    let t2: int = time_ms()
    var suma: int = 0
    var i: int = 0
    while i < 1000000 {
        suma = suma + i
        i = i + 1
    }
    let t3: int = time_ms()
    let dur: int = t3 - t2
    print("suma de 0..1M = " + int_to_string(suma))
    print("duracion loop: " + int_to_string(dur) + "ms")

    return 0
}

Output

start
500ms passed
tiempo real: 500ms
suma de 0..1M = 499999500000
duracion loop: 0ms

Explanation

time_ms() is a thin wrapper around the system clock, returning a monotonic millisecond timestamp suitable for duration measurements. Taking the difference t1 - t0 after a sleep(500) should produce a value at or just above 500, depending on OS scheduler precision.

The second measurement wraps a tight loop summing integers from 0 to 999 999. The result — 499 999 500 000 — is the standard arithmetic series sum n*(n-1)/2 for n = 1 000 000. The duration rounds to 0ms because LLVM optimizes the loop aggressively at native code generation time.

Both time_ms and sleep are built-in functions available without any import. They are implemented in the runtime's time.c module and map directly to clock_gettime(CLOCK_MONOTONIC) and nanosleep on Linux.

← Previous Next →

Source: examples/by-example/37-sleep-timer.nx