nx_time_canonical.nx source
↩ module page · 78 lines · 2640 B
1const CLOCK_MAGIC_1000000000: i64 = 1000000000
2const CLOCK_MAGIC_1577836800000000000: i64 = 1577836800000000000
3// time.nx -- monotonic + wall clock, via Linux/NishiOS clock_gettime.
4//
5// Zero third-party runtime: only __syscall. Syscall 113 is
6// clock_gettime(clk_id, *timespec); returns 0 on success, -1 on error.
7// Linux RV64 numbers; NishiOS keeps the same set.
8//
9// TimeSpec layout matches Linux's `struct timespec`: two i64 fields,
10// seconds + nanoseconds. `var ts: TimeSpec` stack-allocates via the
11// compiler's alloca path; `&ts` hands the kernel a pointer to write
12// into.
13//
14// Callers generally want ns since some origin:
15// * monotonic_ns() -- ns since boot; cannot go backwards; immune to
16// wall-clock jumps (NTP, DST, manual set). Use for timing.
17// * wall_clock_ns() -- ns since Unix epoch; CAN jump. Use only for
18// human-readable timestamps and inter-machine correlation.
19
20// ---- syscall helpers ----
21
22const CLOCK_REALTIME: i64 = 0
23const CLOCK_MONOTONIC: i64 = 1
24
25struct TimeSpec {
26 sec: i64,
27 nsec: i64,
28}
29
30func sys_clock_gettime(clk_id: i64, ts: *TimeSpec) -> i64 {
31 return __syscall(113, clk_id, ts as i64, 0, 0, 0, 0)
32}
33
34// ---- public API ----
35
36// Nanoseconds since an unspecified monotonic origin (typically boot).
37// Non-decreasing, insensitive to wall-clock adjustments.
38func monotonic_ns() -> i64 {
39 var ts: TimeSpec
40 ts.sec = 0
41 ts.nsec = 0
42 sys_clock_gettime(CLOCK_MONOTONIC, &ts)
43 return ts.sec * CLOCK_MAGIC_1000000000 + ts.nsec
44}
45
46// Nanoseconds since the Unix epoch (1970-01-01 00:00:00 UTC).
47// Can jump backward on clock adjustment; prefer monotonic_ns for
48// measuring durations.
49func wall_clock_ns() -> i64 {
50 var ts: TimeSpec
51 ts.sec = 0
52 ts.nsec = 0
53 sys_clock_gettime(CLOCK_REALTIME, &ts)
54 return ts.sec * CLOCK_MAGIC_1000000000 + ts.nsec
55}
56
57// ===== self-test ===================================================
58//
59// Two cheap invariants:
60// * monotonic never decreases between two successive samples
61// * wall clock is positive and past 2020-01-01 (1577836800 seconds)
62//
63// Returns 0 on success; a small failure code indicates which check
64// failed (keeps the binary single-entry-point and diffable).
65
66func main() -> i64 {
67 let m1: i64 = monotonic_ns()
68 let m2: i64 = monotonic_ns()
69 if m2 < m1 { return 1 }
70 if m1 <= 0 { return 2 }
71
72 let w: i64 = wall_clock_ns()
73 // 2020-01-01 in ns. Any sane build machine passes.
74 let epoch_2020_ns: i64 = CLOCK_MAGIC_1577836800000000000
75 if w < epoch_2020_ns { return 3 }
76
77 return 0
78}