| ... | @@ -580,3 +580,46 @@ pub fn microTimestamp() i64 { | ... | @@ -580,3 +580,46 @@ pub fn microTimestamp() i64 { |
| 580 | pub fn milliTimestamp() i64 { | 580 | pub fn milliTimestamp() i64 { |
| 581 | return @as(i64, @intCast(@divFloor(nanoTimestamp(), ns_per_ms))); | 581 | return @as(i64, @intCast(@divFloor(nanoTimestamp(), ns_per_ms))); |
| 582 | } | 582 | } |
| | 583 | |
| | 584 | pub 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 | |
| | 601 | pub 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 | }; |