const std = @import("std"); const Writer = std.Io.Writer; /// Measures on the monotonic clock, for lines that say how long a step took. pub const Stopwatch = struct { started: std.Io.Timestamp, pub fn start() Stopwatch { return .{ .started = now() }; } pub fn elapsed(self: Stopwatch) Elapsed { return .{ .duration = self.started.durationTo(now()) }; } pub const Elapsed = struct { duration: std.Io.Duration, pub fn format(self: Elapsed, writer: *Writer) Writer.Error!void { const millis = @as(f64, @floatFromInt(self.duration.nanoseconds)) / std.time.ns_per_ms; try writer.print("{d:.1} ms", .{millis}); } }; }; /// Measures a step repeated many times, for lines that say how long it took /// in all and how long each time took. Keeps running statistics rather than /// every lap, so it needs no allocator however many laps there are. pub const LapTimer = struct { laps: usize = 0, mark: std.Io.Timestamp, mean_ns: f64 = 0, /// The sum of squared deviations from the mean, which Welford's online /// algorithm updates lap by lap. squared_deviations: f64 = 0, total: std.Io.Duration = .zero, pub fn start() LapTimer { return .{ .mark = now() }; } /// Ends the lap begun at the previous lap, or at the start. pub fn lap(self: *LapTimer) void { const ended = now(); self.add(self.mark.durationTo(ended)); self.mark = ended; } /// Counts a lap timed elsewhere, for a caller with work between laps that /// must not be counted. pub fn add(self: *LapTimer, duration: std.Io.Duration) void { self.laps += 1; self.total.nanoseconds += duration.nanoseconds; const lap_ns: f64 = @floatFromInt(duration.nanoseconds); const delta = lap_ns - self.mean_ns; self.mean_ns += delta / @as(f64, @floatFromInt(self.laps)); self.squared_deviations += delta * (lap_ns - self.mean_ns); } /// The laps ended so far; time since the last one is not counted. pub fn elapsed(self: LapTimer) Elapsed { return .{ .laps = self.laps, .mean_ns = self.mean_ns, .stddev_ns = if (self.laps < 2) null else @sqrt(self.squared_deviations / @as(f64, @floatFromInt(self.laps - 1))), .total = self.total, }; } pub const Elapsed = struct { laps: usize, mean_ns: f64, /// The sample standard deviation, which takes at least two laps. stddev_ns: ?f64, total: std.Io.Duration, pub fn format(self: Elapsed, writer: *Writer) Writer.Error!void { try writer.print("{d} × ", .{self.laps}); if (self.laps == 0) { try writer.writeAll("–"); } else { try writer.print("{d:.1}", .{self.mean_ns / std.time.ns_per_us}); if (self.stddev_ns) |stddev| try writer.print(" ± {d:.1}", .{stddev / std.time.ns_per_us}); try writer.writeAll(" µs"); } try writer.print(" = {f}", .{Stopwatch.Elapsed{ .duration = self.total }}); } }; }; fn now() std.Io.Timestamp { return .now(std.Options.debug_io, .awake); } const expectApproxEqRel = std.testing.expectApproxEqRel; const expectEqual = std.testing.expectEqual; const expectFmt = std.testing.expectFmt; test "an elapsed time reads in milliseconds to a tenth" { try expectFmt("0.4 ms", "{f}", .{Stopwatch.Elapsed{ .duration = .fromNanoseconds(412_345) }}); try expectFmt("400.2 ms", "{f}", .{Stopwatch.Elapsed{ .duration = .fromNanoseconds(400_212_000) }}); } test "laps add up to the total and spread by their sample standard deviation" { var timer: LapTimer = .start(); for ([_]i64{ 1, 2, 3, 4 }) |millis| timer.add(.fromMilliseconds(millis)); const elapsed = timer.elapsed(); try expectEqual(10 * std.time.ns_per_ms, elapsed.total.nanoseconds); try expectEqual(4, elapsed.laps); try expectApproxEqRel(2.5 * std.time.ns_per_ms, elapsed.mean_ns, 1e-9); // sqrt(5/3) ms: the squared deviations summed, over n - 1. try expectApproxEqRel(1.2909944487 * std.time.ns_per_ms, elapsed.stddev_ns.?, 1e-9); } test "a single lap has no spread" { var timer: LapTimer = .start(); timer.add(.fromMilliseconds(3)); const elapsed = timer.elapsed(); try expectEqual(1, elapsed.laps); try expectApproxEqRel(3.0 * std.time.ns_per_ms, elapsed.mean_ns, 1e-9); try expectEqual(null, elapsed.stddev_ns); } test "a lap timer with no laps has taken no time" { const timer: LapTimer = .start(); const elapsed = timer.elapsed(); try expectEqual(0, elapsed.laps); try expectEqual(0, elapsed.total.nanoseconds); try expectEqual(null, elapsed.stddev_ns); } test "laps read as their count times the time per lap in microseconds, then the total" { try expectFmt("1200 × 344.1 ± 51.2 µs = 412.3 ms", "{f}", .{LapTimer.Elapsed{ .laps = 1200, .mean_ns = 344_123.4, .stddev_ns = 51_234.5, .total = .fromNanoseconds(412_345_678), }}); try expectFmt("1 × 344.1 µs = 0.3 ms", "{f}", .{LapTimer.Elapsed{ .laps = 1, .mean_ns = 344_123.0, .stddev_ns = null, .total = .fromNanoseconds(344_123), }}); try expectFmt("0 × – = 0.0 ms", "{f}", .{LapTimer.Elapsed{ .laps = 0, .mean_ns = 0, .stddev_ns = null, .total = .zero, }}); }