Skip to main content

quickjs_jit_stdlib/llrt/llrt_utils/
time.rs

1// Vendored from LLRT d9fd873e793c (libs/llrt_utils/src/time.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py.
3use std::{
4    sync::atomic::{AtomicU64, Ordering},
5    time::SystemTime,
6};
7
8static TIME_ORIGIN: AtomicU64 = AtomicU64::new(0);
9
10/// Get the current time in nanoseconds.
11///
12/// # Safety
13/// - Good until the year 2554
14/// - Always use a checked substraction since this can return 0
15pub fn now_nanos() -> u64 {
16    SystemTime::now()
17        .duration_since(std::time::UNIX_EPOCH)
18        .unwrap_or_default()
19        .as_nanos() as u64
20}
21
22/// Get the current time in millis.
23///
24/// # Safety
25/// - Good until the year 2554
26/// - Always use a checked substraction since this can return 0
27pub fn now_millis() -> i64 {
28    SystemTime::now()
29        .duration_since(std::time::UNIX_EPOCH)
30        .unwrap_or_default()
31        .as_millis() as i64
32}
33
34/// Get the origin time in nanoseconds.
35///
36/// # Safety
37/// - Good until the year 2554
38/// - Always use a checked substraction since this can return 0
39pub fn origin_nanos() -> u64 {
40    TIME_ORIGIN.load(Ordering::Relaxed)
41}
42
43// For accuracy reasons, this function should be executed when the vm is initialized
44pub fn init() {
45    if TIME_ORIGIN.load(Ordering::Relaxed) == 0 {
46        let time_origin = now_nanos();
47        TIME_ORIGIN.store(time_origin, Ordering::Relaxed)
48    }
49}