diff options
Diffstat (limited to 'src/FrameStats.zig')
| -rw-r--r-- | src/FrameStats.zig | 327 |
1 files changed, 327 insertions, 0 deletions
diff --git a/src/FrameStats.zig b/src/FrameStats.zig new file mode 100644 index 00000000..74f875df --- /dev/null +++ b/src/FrameStats.zig @@ -0,0 +1,327 @@ +//! The frame-timing probe a game keeps: for every frame the pump draws, how +//! long its update, its render and its present took on the clock, the gap +//! since the frame before, and what the shell's own motion (a scroll's +//! picture) showed in it. A frame that something was +//! animating into and that came more than half a display period late is +//! jank: the eye sees the motion stop for a refresh. The records go in a +//! fixed ring embedded in `Pardes`, nothing allocated per frame, and cost +//! three reads of the monotonic clock a frame, so the probe is always on: +//! `Debug` shows the last second of it in its box, and `PARDES_FRAMES=path` +//! writes the whole ring and its summary there when the session ends. +//! +//! `PARDES_FRAMES_DEMO=scroll` runs `demo`, a timed script of scroll +//! inputs, in a pixel shell (the GUI feeds them through its own wheel and +//! key paths) and then ends the session: a timedemo, so two builds are +//! compared on the same motion, on a real display. +const std = @import("std"); +const pardes = @import("pardes.zig"); +const animation = @import("animation.zig"); + +const FrameStats = @This(); + +/// 68 s at 60 Hz: a scripted run fits whole. +/// ponytail: a fixed ring, a file-backed log if a session's whole history matters. +pub const capacity = 4096; + +pub const Frame = struct { + /// When the frame's step began, the input that woke it read: the + /// monotonic clock, ns. + start_ns: u64 = 0, + /// Events, effects and the shell's poll; the core's render; the + /// shell's present (its instance build and GPU submission). µs. + update_us: u32 = 0, + render_us: u32 = 0, + present_us: u32 = 0, + /// From the previous drawn frame's present to this one's, µs. + gap_us: u32 = 0, + /// Something was moving into this frame: the gap should be a period. + moving: bool = false, + /// The shell had no image to draw into (a busy swapchain). + skipped: bool = false, + /// The shell's motion in it: a scroll's picture offset from the text, + /// rows (0 at rest). + scroll: f32 = 0, +}; + +ring: [capacity]Frame = @splat(.{}), +/// Frames recorded since the start; the ring holds the last `capacity`. +count: u64 = 0, +/// The display's refresh period, as the shell knows it. +period_ns: u64 = animation.frame_ns, +/// The end of the last drawn frame's present, and whether anything was +/// still moving then (the next frame was owed at once). +last_end_ns: u64 = 0, +armed: bool = false, +/// Since the start: frames that came late into a motion, and frames whose +/// own work (update, render, present) took longer than a period. +jank: u64 = 0, +over_budget: u64 = 0, +skipped: u64 = 0, +/// What the shell sets while it draws the frame (Frame.scroll). +scroll: f32 = 0, +/// The frame being timed: its marks, the monotonic clock's ns. +mark_start: u64 = 0, +mark_update: u64 = 0, +mark_render: u64 = 0, + +pub fn nowNs() u64 { + if (comptime !pardes.hosted) return 0; + var ts: std.c.timespec = undefined; + if (std.c.clock_gettime(.MONOTONIC, &ts) != 0) return 0; + return @as(u64, @intCast(ts.sec)) *| std.time.ns_per_s +| @as(u64, @intCast(ts.nsec)); +} + +/// Closes the frame whose marks are set: `end_ns` is when its present +/// returned, `moving` whether anything still moves (a frame is owed at +/// once), `skipped` whether the shell drew nothing. +pub fn record(stats: *FrameStats, end_ns: u64, moving: bool, skipped: bool) void { + const us = struct { + fn of(from: u64, to: u64) u32 { + return @intCast(@min(std.math.maxInt(u32), (to -| from) / std.time.ns_per_us)); + } + }; + const gap: u32 = if (stats.last_end_ns == 0) 0 else us.of(stats.last_end_ns, end_ns); + const frame: Frame = .{ + .start_ns = stats.mark_start, + .update_us = us.of(stats.mark_start, stats.mark_update), + .render_us = us.of(stats.mark_update, stats.mark_render), + .present_us = us.of(stats.mark_render, end_ns), + .gap_us = gap, + .moving = stats.armed, + .skipped = skipped, + .scroll = stats.scroll, + }; + // Half a period late is a refresh the motion missed. + if (stats.armed and @as(u64, gap) * std.time.ns_per_us * 2 > stats.period_ns * 3) stats.jank += 1; + if (@as(u64, frame.update_us + frame.render_us + frame.present_us) * std.time.ns_per_us > stats.period_ns) stats.over_budget += 1; + if (skipped) stats.skipped += 1; + stats.ring[stats.count % capacity] = frame; + stats.count += 1; + stats.last_end_ns = end_ns; + stats.armed = moving; +} + +/// The last `n` frames, oldest first, as two slices of the ring. +pub fn last(stats: *const FrameStats, n: usize) [2][]const Frame { + const have: usize = @intCast(@min(stats.count, capacity)); + const take = @min(n, have); + const end: usize = @intCast(stats.count % capacity); + if (take <= end) return .{ stats.ring[end - take .. end], &.{} }; + return .{ stats.ring[capacity - (take - end) ..], stats.ring[0..end] }; +} + +/// Order statistics of one of a run of frames' times, µs: its median, +/// 99th percentile and worst; over the moving frames only for a gap. +pub const Spread = struct { + n: usize = 0, + p50: u32 = 0, + p90: u32 = 0, + p99: u32 = 0, + max: u32 = 0, + mean: f64 = 0, + + pub const What = enum { work, update, render, present, gap }; + + pub fn of(frames: [2][]const Frame, comptime what: What) Spread { + var values: [capacity]u32 = undefined; + var n: usize = 0; + var sum: f64 = 0; + for (frames) |part| for (part) |f| { + const v: u32 = switch (what) { + .work => f.update_us + f.render_us + f.present_us, + .update => f.update_us, + .render => f.render_us, + .present => f.present_us, + .gap => if (f.moving) f.gap_us else continue, + }; + values[n] = v; + n += 1; + sum += @floatFromInt(v); + }; + if (n == 0) return .{}; + std.mem.sortUnstable(u32, values[0..n], {}, std.sort.asc(u32)); + return .{ + .n = n, + .p50 = values[n / 2], + .p90 = values[@min(n - 1, n * 90 / 100)], + .p99 = values[@min(n - 1, n * 99 / 100)], + .max = values[n - 1], + .mean = sum / @as(f64, @floatFromInt(n)), + }; + } +}; + +/// The Debug box's lines: the last second's work and gaps, and the +/// counters since the start, in ms. +pub fn summary(stats: *const FrameStats, buf: []u8) []const u8 { + const recent = stats.last(@intCast(@max(1, std.time.ns_per_s / @max(1, stats.period_ns)))); + const work = Spread.of(recent, .work); + const gap = Spread.of(recent, .gap); + return std.fmt.bufPrint(buf, "frame {d:.2}/{d:.2}/{d:.2} ms\ngap {d:.2}/{d:.2} ms jank {d}", .{ + @as(f64, @floatFromInt(work.p50)) / 1000, @as(f64, @floatFromInt(work.p99)) / 1000, @as(f64, @floatFromInt(work.max)) / 1000, + @as(f64, @floatFromInt(gap.p50)) / 1000, @as(f64, @floatFromInt(gap.max)) / 1000, stats.jank, + }) catch ""; +} + +/// Writes the summary and every frame the ring holds to `path`: a header +/// of `# ` lines, then one tab-separated line a frame. +pub fn dump(stats: *const FrameStats, path: [:0]const u8) void { + if (comptime !pardes.hosted) return; + const fd = std.c.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true, .CLOEXEC = true }, @as(std.c.mode_t, 0o644)); + if (fd < 0) return; + defer _ = std.c.close(fd); + var buf: [256]u8 = undefined; + const all = stats.last(capacity); + const write = struct { + fn line(f: c_int, b: []u8, comptime fmt: []const u8, args: anytype) void { + const text = std.fmt.bufPrint(b, fmt, args) catch return; + _ = std.c.write(f, text.ptr, text.len); + } + }; + write.line(fd, &buf, "# frames {d} period_us {d} jank {d} over_budget {d} skipped {d}\n", .{ stats.count, stats.period_ns / std.time.ns_per_us, stats.jank, stats.over_budget, stats.skipped }); + inline for (comptime std.enums.values(Spread.What)) |what| { + const s = Spread.of(all, what); + write.line(fd, &buf, "# {t} n {d} mean {d:.0} p50 {d} p90 {d} p99 {d} max {d}\n", .{ what, s.n, s.mean, s.p50, s.p90, s.p99, s.max }); + } + write.line(fd, &buf, "# start_ms\tupdate_us\trender_us\tpresent_us\tgap_us\tmoving\tskipped\tscroll\n", .{}); + const t0 = if (all[0].len != 0) all[0][0].start_ns else 0; + for (all) |part| for (part) |f| { + write.line(fd, &buf, "{d:.3}\t{d}\t{d}\t{d}\t{d}\t{d}\t{d}\t{d:.4}\n", .{ + @as(f64, @floatFromInt(f.start_ns -| t0)) / std.time.ns_per_ms, f.update_us, f.render_us, f.present_us, f.gap_us, + @intFromBool(f.moving), @intFromBool(f.skipped), f.scroll, + }); + }; +} + +/// One input of the scroll timedemo, `at_ms` after the first frame. +pub const Step = struct { + at_ms: u32, + act: union(enum) { + /// Wheel notches, down positive, as a mouse's. + wheel: i8, + key: pardes.Key, + /// The run is over: the session ends. + end, + }, +}; + +/// Every kind of scroll a user makes, on a long file from its top: single +/// notches, a fast spin of the wheel both ways (notches 8 ms apart, two a +/// frame: each retargets the one before), half pages, pages, the far jumps +/// to the end and back, half pages faster than they settle, and the cursor +/// moving a line, a word and, in insert mode, a column at a time. +pub const demo = blk: { + @setEvalBranchQuota(20_000); + var steps: [128]Step = undefined; + var n: usize = 0; + var t: u32 = 1500; + for (0..10) |_| { + steps[n] = .{ .at_ms = t, .act = .{ .wheel = 1 } }; + n += 1; + t += 150; + } + t += 400; + for ([_]i8{ 1, -1 }) |dir| { + for (0..24) |_| { + steps[n] = .{ .at_ms = t, .act = .{ .wheel = dir } }; + n += 1; + t += 8; + } + t += 800; + } + const ctrl = struct { + fn key(cp: u21) pardes.Key { + return .{ .cp = cp, .ctrl = true }; + } + }; + for ([_]u21{ 'd', 'd', 'd', 'u', 'u', 'f', 'b' }) |cp| { + steps[n] = .{ .at_ms = t, .act = .{ .key = ctrl.key(cp) } }; + n += 1; + t += 600; + } + steps[n] = .{ .at_ms = t, .act = .{ .key = .{ .cp = 'G', .text = "G" } } }; + n += 1; + t += 800; + for (0..2) |i| { + steps[n] = .{ .at_ms = t + 20 * i, .act = .{ .key = .{ .cp = 'g', .text = "g" } } }; + n += 1; + } + t += 800; + for (0..4) |_| { + steps[n] = .{ .at_ms = t, .act = .{ .key = ctrl.key('d') } }; + n += 1; + t += 80; + } + t += 700; + for ([_]struct { u21, []const u8, u32 }{ .{ 'j', "j", 60 }, .{ 'w', "w", 90 } }) |run| { + for (0..10) |_| { + steps[n] = .{ .at_ms = t, .act = .{ .key = .{ .cp = run[0], .text = run[1] } } }; + n += 1; + t += run[2]; + } + t += 400; + } + steps[n] = .{ .at_ms = t, .act = .{ .key = .{ .cp = 'i', .text = "i" } } }; + n += 1; + t += 300; + for ([_]struct { u21, u32 }{ .{ pardes.Key.right, 60 }, .{ pardes.Key.down, 100 } }) |run| { + for (0..8) |_| { + steps[n] = .{ .at_ms = t, .act = .{ .key = .{ .cp = run[0] } } }; + n += 1; + t += run[1]; + } + t += 300; + } + steps[n] = .{ .at_ms = t, .act = .{ .key = .{ .cp = pardes.Key.escape } } }; + steps[n + 1] = .{ .at_ms = t + 1000, .act = .end }; + n += 2; + const out = steps[0..n].*; + break :blk out; +}; + +test "frame stats: gaps into a motion count as jank, idle gaps do not, and the ring keeps the last frames" { + var stats: FrameStats = .{ .period_ns = 16 * std.time.ns_per_ms }; + const ms = std.time.ns_per_ms; + var t: u64 = 1000 * ms; + // An idle frame, then a second of nothing: no jank, nothing was moving. + stats.mark_start = t; + stats.mark_update = t + ms; + stats.mark_render = t + 2 * ms; + stats.record(t + 3 * ms, false, false); + t += 1000 * ms; + // A frame after the pause starts a motion; then one on time, then one + // two periods late. + for ([_]u64{ 16, 16, 33 }) |late| { + t += late * ms; + stats.mark_start = t - ms; + stats.mark_update = t - ms; + stats.mark_render = t - ms; + stats.record(t, true, false); + } + try std.testing.expectEqual(@as(u64, 1), stats.jank); + try std.testing.expectEqual(@as(u64, 4), stats.count); + const recent = stats.last(3); + try std.testing.expectEqual(@as(u32, 1_013_000), recent[0][0].gap_us); + try std.testing.expect(!recent[0][0].moving and recent[0][1].moving); + try std.testing.expectEqual(@as(u32, 33_000), recent[0][2].gap_us); + // Only the frames something moved into have a gap that counts. + const gap = Spread.of(stats.last(capacity), .gap); + try std.testing.expectEqual(@as(usize, 2), gap.n); + try std.testing.expectEqual(@as(u32, 33_000), gap.max); + // Round the ring: still the last ones, oldest first. + for (0..capacity + 5) |i| { + stats.mark_start = t; + stats.mark_update = t; + stats.mark_render = t; + t += 16 * ms; + stats.scroll = @floatFromInt(i); + stats.record(t, true, false); + } + const tail = stats.last(10); + try std.testing.expectEqual(@as(usize, 10), tail[0].len + tail[1].len); + const newest = if (tail[1].len != 0) tail[1][tail[1].len - 1] else tail[0][tail[0].len - 1]; + try std.testing.expectEqual(@as(f32, capacity + 4), newest.scroll); + // The demo ends, and its steps are in time order. + try std.testing.expect(demo[demo.len - 1].act == .end); + for (demo[1..], demo[0 .. demo.len - 1]) |b, a| try std.testing.expect(b.at_ms >= a.at_ms); +} |
