From 99f5b10eccd95aa0066ea6fe6bb75f367ab56a47 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 18 Nov 2026 22:03:14 -0300 Subject: core: src/ becomes core/, pardes.zig its root.zig (the reorganisation's tree, step 2d), and every mention of a src/ path follows: the build's paths, the core's imports of its root, the tests that read the repository's files by path (lspbench's, look.zig's spans over core/look.zig), the comments that cite files, the documents and the manual (the typst corpus reads core/tutor.txt and core/plumbing); left as they were: the /src tree's served names (src/pardes.zig and the rest are the 9P tree's, not the repository's), the CHANGELOG's history, fixtures that are only strings; fs-unit-test runs from the core's root (a module of the core rooted at fs.zig had the runtime's and the devices' `core` be fs.zig); nothing else changes: the ledger (pardes.test.* now root.test.*), frames byte-identical, replicas and process-test the base's Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/FrameStats.zig | 531 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 531 insertions(+) create mode 100644 core/FrameStats.zig (limited to 'core/FrameStats.zig') diff --git a/core/FrameStats.zig b/core/FrameStats.zig new file mode 100644 index 00000000..4fbe0735 --- /dev/null +++ b/core/FrameStats.zig @@ -0,0 +1,531 @@ +//! 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` +//! keeps a longer ring (`long_capacity`, from the first frame) and writes +//! it and its summary there when the session ends. +//! +//! Each frame also carries its input-to-present latency (from the first +//! input it answers, the shell's timestamp of the key or wheel event, to +//! the end of its present), where its work went (`Zone`: the core's body +//! text, rows and colours; the shell's instance build, word shaping and +//! glyph rasterizing) and the view it showed, so a spike is attributed and +//! a scroll's throughput is counted in rows actually presented. +//! +//! `PARDES_FRAMES_DEMO=` runs a timed script of inputs (`parseScript`; +//! the ones the notes measured with are in tools/demos/) 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("root.zig"); +const frame_ns = @import("root.zig").frame_ns; + +const FrameStats = @This(); + +/// The frames every core keeps (90 KB), what the Debug box reads: the +/// last second's, and the input latency over all of them. +pub const capacity = 1024; +/// The frames a core keeps with PARDES_FRAMES set: 4.5 minutes at 60 Hz, +/// so the longest timedemo fits whole (1.4 MB, allocated at the first). +pub const long_capacity = 16384; + +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), or a focused PDF's strip as drawn, pixels down + /// the document; and where it drew the caret, its top in rows (the + /// jitter check: a caret on a fixed row must not wobble). + scroll: f32 = 0, + caret: f32 = 0, + /// From the first input this frame answers to its present's end, µs; + /// 0 when it answers none. + latency_us: u32 = 0, + /// The focused pane's first line: with `scroll`, where the picture is. + view: i32 = 0, + /// µs a frame spent in each zone, and how many words the shell shaped + /// and glyphs it rasterized anew. + zones: [zone_count]u32 = @splat(0), + shaped: u16 = 0, + rastered: u16 = 0, + /// Bytes a cell shell wrote to its terminal for the frame. + bytes: u32 = 0, + /// PDF page rasters that landed in it (rendered on the loop, or taken + /// from a lane): the frame a page lands on. + landed: u16 = 0, +}; + +/// Where a frame's work goes, as a game's profiler splits its budget. +/// The gui's are nested: shape and raster inside build; a soft present's +/// wait for the GPU, its upload of the frame and its flip after it. +pub const Zone = enum(u8) { body_text, body_rows, body_color, gui_build, gui_shape, gui_raster, gui_wait, gui_upload, gui_flip }; +pub const zone_count = std.enums.values(Zone).len; + +ring: [capacity]Frame = @splat(.{}), +/// PARDES_FRAMES's ring, which takes the frames in place of `ring`. +long: ?*[long_capacity]Frame = null, +/// Frames recorded since the start; the ring holds the last of them. +count: u64 = 0, +/// The display's refresh period, as the shell knows it. +period_ns: u64 = 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), and the +/// pump (view). +scroll: f32 = 0, +caret: f32 = 0, +view: i32 = 0, +/// The first input not yet answered by a drawn frame, monotonic ns. +input_ns: u64 = 0, +/// This frame's zones so far. +zone_us: [zone_count]u32 = @splat(0), +shaped: u16 = 0, +rastered: u16 = 0, +bytes: u32 = 0, +landed: u16 = 0, +/// When the timedemo started, monotonic ns (0: none ran), and its steps. +demo_ns: u64 = 0, +demo: []const Step = &.{}, +/// The frame being timed: its marks, the monotonic clock's ns. +mark_start: u64 = 0, +mark_update: u64 = 0, +mark_render: u64 = 0, + +/// An input arrived at `at_ns`: the next drawn frame answers it. +pub fn input(stats: *FrameStats, at_ns: u64) void { + if (stats.input_ns == 0 or at_ns < stats.input_ns) stats.input_ns = at_ns; +} + +/// The pump had nothing to draw: what came in changed nothing on screen, +/// so no frame answers it. +pub fn idle(stats: *FrameStats) void { + stats.input_ns = 0; + // Nor was a frame owed after all (a motion that ended between frames): + // the next frame's gap is no motion's. + stats.armed = false; +} + +/// Adds the time since `from_ns` to `which`. +pub fn zone(stats: *FrameStats, which: Zone, from_ns: u64) void { + const us: u32 = @intCast(@min(std.math.maxInt(u32), (nowNs() -| from_ns) / std.time.ns_per_us)); + stats.zone_us[@backingInt(which)] +|= us; +} + +pub fn nowNs() u64 { + 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, + .caret = stats.caret, + .latency_us = if (stats.input_ns == 0) 0 else @max(1, us.of(stats.input_ns, end_ns)), + .view = stats.view, + .zones = stats.zone_us, + .shaped = stats.shaped, + .rastered = stats.rastered, + .bytes = stats.bytes, + .landed = stats.landed, + }; + stats.bytes = 0; + stats.landed = 0; + stats.input_ns = 0; + stats.zone_us = @splat(0); + stats.shaped = 0; + stats.rastered = 0; + // 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; + if (stats.count == 0 and std.c.getenv("PARDES_FRAMES") != null) { + stats.long = std.heap.page_allocator.create([long_capacity]Frame) catch null; + } + const ring: []Frame = if (stats.long) |long| long else &stats.ring; + ring[@intCast(stats.count % ring.len)] = 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 ring: []const Frame = if (stats.long) |long| long else &stats.ring; + const have: usize = @intCast(@min(stats.count, ring.len)); + const take = @min(n, have); + const end: usize = @intCast(stats.count % ring.len); + if (take <= end) return .{ ring[end - take .. end], &.{} }; + return .{ ring[ring.len - (take - end) ..], 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, latency }; + + pub fn of(frames: [2][]const Frame, comptime what: What) Spread { + var values: [long_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, + .latency => if (f.latency_us != 0) f.latency_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, gaps and input latency, +/// and the jank counter since the start, in ms. +pub fn summary(stats: *const FrameStats, buf: *[summary_max]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); + const latency = Spread.of(stats.last(capacity), .latency); + const ms = struct { + fn of(v: u32) f64 { + return @as(f64, @floatFromInt(v)) / 1000; + } + }; + return std.fmt.bufPrint(buf, "frame {d:.2}/{d:.2}/{d:.2} ms\ngap {d:.2}/{d:.2} ms jank {d}\ninput {d:.2}/{d:.2} ms", .{ + ms.of(work.p50), ms.of(work.p99), ms.of(work.max), ms.of(gap.p50), ms.of(gap.max), stats.jank, ms.of(latency.p50), ms.of(latency.p90), + }) catch unreachable; // summary_max holds the widest +} + +/// `summary`'s widest: its words, seven u32 µs in ms with two places +/// (`4294967.30`) and a u64. +pub const summary_max = 132; + +/// Writes the summary and every frame the ring holds to `path`: a header +/// of `# ` lines, then one tab-separated line a frame. The long ring goes. +pub fn dump(stats: *FrameStats, path: [:0]const u8) void { + defer if (stats.long) |long| { + std.heap.page_allocator.destroy(long); + stats.long = null; + }; + 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(long_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 }); + } + const t0 = if (all[0].len != 0) all[0][0].start_ns else 0; + // The monotonic clock is the machine's: a driver lines its own times + // up with the frames' by this. + write.line(fd, &buf, "# t0_ns {d}\n", .{t0}); + // The timedemo's phases, on the frames' clock. + for (stats.demo) |step| switch (step.act) { + .phase => |name| write.line(fd, &buf, "# phase {s} {d:.1}\n", .{ name, @as(f64, @floatFromInt((stats.demo_ns + @as(u64, step.at_ms) * std.time.ns_per_ms) -| t0)) / std.time.ns_per_ms }), + else => {}, + }; + write.line(fd, &buf, "# start_ms\tupdate_us\trender_us\tpresent_us\tgap_us\tmoving\tskipped\tscroll\tcaret\tlatency_us\tview", .{}); + inline for (comptime std.enums.values(Zone)) |which| write.line(fd, &buf, "\t{t}_us", .{which}); + write.line(fd, &buf, "\tshaped\trastered\tbytes\tlanded\n", .{}); + 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}\t{d:.4}\t{d}\t{d}", .{ + @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, f.caret, f.latency_us, f.view, + }); + for (f.zones) |us| write.line(fd, &buf, "\t{d}", .{us}); + write.line(fd, &buf, "\t{d}\t{d}\t{d}\t{d}\n", .{ f.shaped, f.rastered, f.bytes, f.landed }); + }; +} + +/// One input of a 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, + /// A touchpad's scroll, lines down, a fraction (no notch). + touch: f32, + key: pardes.Key, + /// A named stretch of the run starts (the dump lists them). + phase: []const u8, + /// A press and release of `button` over the focused pane, `at` of + /// the way down its body, on its rail or in its text. + click: struct { button: pardes.Mouse.Button, at: f32, rail: bool }, + /// Wheel notches over the focused pane's rail (the gutter). + rail_wheel: i8, + /// Text pasted (bracketed, as a terminal's paste arrives). + paste: []const u8, + /// A line run as Exec runs it, in the focused pane (a builtin, a + /// setting, else a shell command), the pane it opens focused: what + /// opens the other kinds of pane. + exec: []const u8, + /// The run is over: the session ends. + end, + }, +}; + +/// A timedemo's script, the file PARDES_FRAMES_DEMO names (tools/demos/): an +/// input a line, ` []` at `ms` after the first frame, or +/// ` x []` for n of them `every` ms apart; a +/// line that starts with `#` says what the script is. The actions: `wheel +/// ` (down positive), `touch `, `key `, `keys ...` +/// (its keys in turn, each `every` ms after the one before, n times over), +/// `phase `, `click