From a255e7229febed17d9ff3eddec7252b38ed7b594 Mon Sep 17 00:00:00 2001 From: Meghan Denny Date: Mon, 8 Jun 2026 13:15:58 -0700 Subject: [PATCH] add Instant and Timer --- time.zig | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/time.zig b/time.zig index e5f27db522dce1e991eb688b5b7dc9066e65d35d..9ac346984d42e233ee5aed2c125595076cb0922d 100644 --- a/time.zig +++ b/time.zig @@ -580,3 +580,46 @@ pub fn microTimestamp() i64 { pub fn milliTimestamp() i64 { return @as(i64, @intCast(@divFloor(nanoTimestamp(), ns_per_ms))); } + +pub const Instant = struct { + timestamp_ns: u64, + + pub fn now() !Instant { + const ts = try sys.clock_gettime(sys.CLOCK.REALTIME); + return .{ .timestamp_ns = @as(u64, @intCast(ts.nsec)) + @as(u64, @intCast(ts.sec)) * ns_per_s }; + } + + pub fn since(self: Instant, earlier: Instant) u64 { + return self.timestamp_ns - earlier.timestamp_ns; + } + + pub fn order(self: Instant, other: Instant) std.math.Order { + return std.math.order(self.timestamp_ns, other.timestamp_ns); + } +}; + +pub const Timer = struct { + started: Instant, + + pub fn start() !Timer { + return .{ .started = try .now() }; + } + + fn sample() Instant { + return Instant.now() catch unreachable; + } + + pub fn read(self: *const Timer) u64 { + return sample().since(self.started); + } + + pub fn reset(self: *Timer) void { + self.started = sample(); + } + + pub fn lap(self: *Timer) u64 { + const current = sample(); + defer self.started = current; + return current.since(self.started); + } +}; -- 2.54.0