authorgravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2026-06-08 13:15:58 -07:00
committergravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2026-06-08 13:15:58 -07:00
loga255e7229febed17d9ff3eddec7252b38ed7b594
tree9abc667df426197e5a8ea7dff47536b56f15728a
parenteae2ed2910b661553c1d25f03fc67c66c449e28f
signaturebadge-check Signed by SSH key SHA256:4hHJbtBRU58AYXwjL7fkz2fnQHdiye8x1QpTCQ0sHNw

add Instant and Timer


1 files changed, 43 insertions(+), 0 deletions(-)

time.zig+43
......@@ -580,3 +580,46 @@ pub fn microTimestamp() i64 {
580580pub fn milliTimestamp() i64 {
581581 return @as(i64, @intCast(@divFloor(nanoTimestamp(), ns_per_ms)));
582582}
583
584pub const Instant = struct {
585 timestamp_ns: u64,
586
587 pub fn now() !Instant {
588 const ts = try sys.clock_gettime(sys.CLOCK.REALTIME);
589 return .{ .timestamp_ns = @as(u64, @intCast(ts.nsec)) + @as(u64, @intCast(ts.sec)) * ns_per_s };
590 }
591
592 pub fn since(self: Instant, earlier: Instant) u64 {
593 return self.timestamp_ns - earlier.timestamp_ns;
594 }
595
596 pub fn order(self: Instant, other: Instant) std.math.Order {
597 return std.math.order(self.timestamp_ns, other.timestamp_ns);
598 }
599};
600
601pub const Timer = struct {
602 started: Instant,
603
604 pub fn start() !Timer {
605 return .{ .started = try .now() };
606 }
607
608 fn sample() Instant {
609 return Instant.now() catch unreachable;
610 }
611
612 pub fn read(self: *const Timer) u64 {
613 return sample().since(self.started);
614 }
615
616 pub fn reset(self: *Timer) void {
617 self.started = sample();
618 }
619
620 pub fn lap(self: *Timer) u64 {
621 const current = sample();
622 defer self.started = current;
623 return current.since(self.started);
624 }
625};