master
1const std = @import("std.zig");
2const builtin = @import("builtin");
3const assert = std.debug.assert;
4const testing = std.testing;
5const math = std.math;
6const windows = std.os.windows;
7const posix = std.posix;
8
9pub const epoch = @import("time/epoch.zig");
10
11// Divisions of a nanosecond.
12pub const ns_per_us = 1000;
13pub const ns_per_ms = 1000 * ns_per_us;
14pub const ns_per_s = 1000 * ns_per_ms;
15pub const ns_per_min = 60 * ns_per_s;
16pub const ns_per_hour = 60 * ns_per_min;
17pub const ns_per_day = 24 * ns_per_hour;
18pub const ns_per_week = 7 * ns_per_day;
19
20// Divisions of a microsecond.
21pub const us_per_ms = 1000;
22pub const us_per_s = 1000 * us_per_ms;
23pub const us_per_min = 60 * us_per_s;
24pub const us_per_hour = 60 * us_per_min;
25pub const us_per_day = 24 * us_per_hour;
26pub const us_per_week = 7 * us_per_day;
27
28// Divisions of a millisecond.
29pub const ms_per_s = 1000;
30pub const ms_per_min = 60 * ms_per_s;
31pub const ms_per_hour = 60 * ms_per_min;
32pub const ms_per_day = 24 * ms_per_hour;
33pub const ms_per_week = 7 * ms_per_day;
34
35// Divisions of a second.
36pub const s_per_min = 60;
37pub const s_per_hour = s_per_min * 60;
38pub const s_per_day = s_per_hour * 24;
39pub const s_per_week = s_per_day * 7;
40
41/// An Instant represents a timestamp with respect to the currently
42/// executing program that ticks during suspend and can be used to
43/// record elapsed time unlike `nanoTimestamp`.
44///
45/// It tries to sample the system's fastest and most precise timer available.
46/// It also tries to be monotonic, but this is not a guarantee due to OS/hardware bugs.
47/// If you need monotonic readings for elapsed time, consider `Timer` instead.
48pub const Instant = struct {
49 timestamp: if (is_posix) posix.timespec else u64,
50
51 // true if we should use clock_gettime()
52 const is_posix = switch (builtin.os.tag) {
53 .windows, .uefi, .wasi => false,
54 else => true,
55 };
56
57 /// Queries the system for the current moment of time as an Instant.
58 /// This is not guaranteed to be monotonic or steadily increasing, but for
59 /// most implementations it is.
60 /// Returns `error.Unsupported` when a suitable clock is not detected.
61 pub fn now() error{Unsupported}!Instant {
62 const clock_id = switch (builtin.os.tag) {
63 .windows => {
64 // QPC on windows doesn't fail on >= XP/2000 and includes time suspended.
65 return .{ .timestamp = windows.QueryPerformanceCounter() };
66 },
67 .wasi => {
68 var ns: std.os.wasi.timestamp_t = undefined;
69 const rc = std.os.wasi.clock_time_get(.MONOTONIC, 1, &ns);
70 if (rc != .SUCCESS) return error.Unsupported;
71 return .{ .timestamp = ns };
72 },
73 .uefi => {
74 const value, _ = std.os.uefi.system_table.runtime_services.getTime() catch return error.Unsupported;
75 return .{ .timestamp = value.toEpoch() };
76 },
77 // On darwin, use UPTIME_RAW instead of MONOTONIC as it ticks while
78 // suspended.
79 .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => posix.CLOCK.UPTIME_RAW,
80 // On freebsd derivatives, use MONOTONIC_FAST as currently there's
81 // no precision tradeoff.
82 .freebsd, .dragonfly => posix.CLOCK.MONOTONIC_FAST,
83 // On linux, use BOOTTIME instead of MONOTONIC as it ticks while
84 // suspended.
85 .linux => posix.CLOCK.BOOTTIME,
86 // On other posix systems, MONOTONIC is generally the fastest and
87 // ticks while suspended.
88 else => posix.CLOCK.MONOTONIC,
89 };
90
91 const ts = posix.clock_gettime(clock_id) catch return error.Unsupported;
92 return .{ .timestamp = ts };
93 }
94
95 /// Quickly compares two instances between each other.
96 pub fn order(self: Instant, other: Instant) std.math.Order {
97 // windows and wasi timestamps are in u64 which is easily comparible
98 if (!is_posix) {
99 return std.math.order(self.timestamp, other.timestamp);
100 }
101
102 var ord = std.math.order(self.timestamp.sec, other.timestamp.sec);
103 if (ord == .eq) {
104 ord = std.math.order(self.timestamp.nsec, other.timestamp.nsec);
105 }
106 return ord;
107 }
108
109 /// Returns elapsed time in nanoseconds since the `earlier` Instant.
110 /// This assumes that the `earlier` Instant represents a moment in time before or equal to `self`.
111 /// This also assumes that the time that has passed between both Instants fits inside a u64 (~585 yrs).
112 pub fn since(self: Instant, earlier: Instant) u64 {
113 switch (builtin.os.tag) {
114 .windows => {
115 // We don't need to cache QPF as it's internally just a memory read to KUSER_SHARED_DATA
116 // (a read-only page of info updated and mapped by the kernel to all processes):
117 // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-kuser_shared_data
118 // https://www.geoffchappell.com/studies/windows/km/ntoskrnl/inc/api/ntexapi_x/kuser_shared_data/index.htm
119 const qpc = self.timestamp - earlier.timestamp;
120 const qpf = windows.QueryPerformanceFrequency();
121
122 // 10Mhz (1 qpc tick every 100ns) is a common enough QPF value that we can optimize on it.
123 // https://github.com/microsoft/STL/blob/785143a0c73f030238ef618890fd4d6ae2b3a3a0/stl/inc/chrono#L694-L701
124 const common_qpf = 10_000_000;
125 if (qpf == common_qpf) {
126 return qpc * (ns_per_s / common_qpf);
127 }
128
129 // Convert to ns using fixed point.
130 const scale = @as(u64, std.time.ns_per_s << 32) / @as(u32, @intCast(qpf));
131 const result = (@as(u96, qpc) * scale) >> 32;
132 return @as(u64, @truncate(result));
133 },
134 .uefi, .wasi => {
135 // UEFI and WASI timestamps are directly in nanoseconds
136 return self.timestamp - earlier.timestamp;
137 },
138 else => {
139 // Convert timespec diff to ns
140 const seconds = @as(u64, @intCast(self.timestamp.sec - earlier.timestamp.sec));
141 const elapsed = (seconds * ns_per_s) + @as(u32, @intCast(self.timestamp.nsec));
142 return elapsed - @as(u32, @intCast(earlier.timestamp.nsec));
143 },
144 }
145 }
146};
147
148/// A monotonic, high performance timer.
149///
150/// Timer.start() is used to initialize the timer
151/// and gives the caller an opportunity to check for the existence of a supported clock.
152/// Once a supported clock is discovered,
153/// it is assumed that it will be available for the duration of the Timer's use.
154///
155/// Monotonicity is ensured by saturating on the most previous sample.
156/// This means that while timings reported are monotonic,
157/// they're not guaranteed to tick at a steady rate as this is up to the underlying system.
158pub const Timer = struct {
159 started: Instant,
160 previous: Instant,
161
162 pub const Error = error{TimerUnsupported};
163
164 /// Initialize the timer by querying for a supported clock.
165 /// Returns `error.TimerUnsupported` when such a clock is unavailable.
166 /// This should only fail in hostile environments such as linux seccomp misuse.
167 pub fn start() Error!Timer {
168 const current = Instant.now() catch return error.TimerUnsupported;
169 return Timer{ .started = current, .previous = current };
170 }
171
172 /// Reads the timer value since start or the last reset in nanoseconds.
173 pub fn read(self: *Timer) u64 {
174 const current = self.sample();
175 return current.since(self.started);
176 }
177
178 /// Resets the timer value to 0/now.
179 pub fn reset(self: *Timer) void {
180 const current = self.sample();
181 self.started = current;
182 }
183
184 /// Returns the current value of the timer in nanoseconds, then resets it.
185 pub fn lap(self: *Timer) u64 {
186 const current = self.sample();
187 defer self.started = current;
188 return current.since(self.started);
189 }
190
191 /// Returns an Instant sampled at the callsite that is
192 /// guaranteed to be monotonic with respect to the timer's starting point.
193 fn sample(self: *Timer) Instant {
194 const current = Instant.now() catch unreachable;
195 if (current.order(self.previous) == .gt) {
196 self.previous = current;
197 }
198 return self.previous;
199 }
200};
201
202test Timer {
203 const io = std.testing.io;
204
205 var timer = try Timer.start();
206
207 try std.Io.Clock.Duration.sleep(.{ .clock = .awake, .raw = .fromMilliseconds(10) }, io);
208 const time_0 = timer.read();
209 try testing.expect(time_0 > 0);
210
211 const time_1 = timer.lap();
212 try testing.expect(time_1 >= time_0);
213}
214
215test {
216 _ = epoch;
217}