Skip to content

Minecraft: Java Edition 26.3 rewritten from scratch in Rust, checked against vanilla with 281 differential harnesses. Get it with the Horizon launcher.

Frame pacing benchmark: tools/pacing_bench.py, `stats raw`, spans::laps

Ludovic Maried5273ce67f90
diff --git a/crates/horizon-client-render/src/gfx.rs b/crates/horizon-client-render/src/gfx.rs
index b83131785..d0c872dd6 100644
--- a/crates/horizon-client-render/src/gfx.rs
+++ b/crates/horizon-client-render/src/gfx.rs
@@ -5355,6 +5355,8 @@ impl Renderer {
}
/// `checks`: the error scopes of a scaled screenshot's frame, checked before its PNG is written.
fn draw_frame(&mut self, frame: &Frame, checks: Option<GpuChecks>) -> Result<bool> {
+ // Its steps as spans (HORIZON_SPIKES): each lap names the step that just ended.
+ let mut laps = crate::spans::laps();
let landing = Instant::now();
self.land_frame();
// Waiting for the previous frame (offscreen: at most two on the GPU), not work.
@@ -5410,6 +5412,7 @@ impl Renderer {
}
self.surface_unconfigured = false;
}
+ laps.lap("r_prepare");
// Frame generation: its present thread acquires and presents, this frame draws
// into frames of its own. Not over menus that blur the frame, a shader pack's
// own post passes, HDR or the title screen.
@@ -5536,6 +5539,7 @@ impl Renderer {
let views = self.views(frame);
let pose = frame.bob * frame.spin;
let view_proj = views.primary().view_proj(pose);
+ laps.lap("r_acquire");
// TAA runs where the world post pass does, not under a shader pack's own.
let taa = !frame.title
&& self.pack_post.as_ref().is_none_or(|p| p.1.is_none())
@@ -5678,6 +5682,7 @@ impl Renderer {
};
self.uploads
.buffer(&mut encoder, &self.globals, 0, bytemuck::bytes_of(&globals));
+ laps.lap("r_targets");
// GameRenderer.render3dHud: the hand's projection at hudFov, with the
// bob in its pose rather than the projection (same product).
let hand_projection = Mat4::from_cols_array(&crate::camera::hand_projection(
@@ -5883,6 +5888,7 @@ impl Renderer {
}
self.origins.clear();
let (sections, retiring) = (&self.sections, &self.lod_retiring);
+ laps.lap("r_cameras");
// `LevelRenderer.extractSectionDrawGroups`: each section's `getVisibility`. Once
// nothing is fading (the usual frame), every section is whole without a lookup.
let fade_ms = fade_millis(frame.chunk_fade);
@@ -6064,6 +6070,7 @@ impl Renderer {
self.draw_pages.extend_from_slice(&self.phase2_pages);
let culling = cull.is_some();
let solid_draws = self.draws.len() as u32;
+ laps.lap("r_section_groups");
// LevelRenderer: nearby sections each frame, plus a rotating eighth
// (at least 15) of the visible list. Cached views avoid needless sorts.
self.translucent_draws.clear();
@@ -6261,6 +6268,7 @@ impl Renderer {
(shadow_first + shadow_solid) as usize,
);
let shadow_translucent = self.draws.len() as u32 - shadow_first - shadow_solid;
+ laps.lap("r_nearby");
// Metal replays a multi-draw as one draw call per entry.
self.section_draw_calls = if self.multi_draw && self.info.backend != wgpu::Backend::Metal {
(0..self.section_draws)
@@ -6387,6 +6395,7 @@ impl Renderer {
+ translucent_particle_quads
+ translucent_item_quads
+ oit_entity_quads;
+ laps.lap("r_draw_lists");
// Where the tail of materials the classic and the improved passes
// both draw ends: the shadows, particles and items count back from it.
let base_quads = world_quads - oit_entity_quads;
@@ -6532,6 +6541,7 @@ impl Renderer {
bytemuck::bytes_of(&uniform),
);
}
+ laps.lap("r_materials");
// Every upload before the frame's first pass: a pass ends wgpu-core's
// command buffer, so copies between passes would need one more.
if !frame.screen.is_empty() {
@@ -6658,6 +6668,7 @@ impl Renderer {
.flatten();
}
let pack_reads_world = pack_post || native_post;
+ laps.lap("r_uploads");
// Phase 2 of occlusion culling draws over the depth, and a shader pack or TAA reads it.
let keep_depth = pack_reads_world
|| (taa && self.world_post.taa)
@@ -6789,6 +6800,7 @@ impl Renderer {
}
};
let sky_visible = sky_open(frame);
+ laps.lap("r_world_pass");
// One of Horizon's own packs: this frame's inputs; in a timed frame its sky draws in a
// pass of its own, so that it has a time of its own.
let mut native_sky_pass = false;
@@ -6927,6 +6939,7 @@ impl Renderer {
pass.set_bind_group(0, &self.group, &[]);
sky.draw(&mut pass, &native.frame);
}
+ laps.lap("r_pack_inputs");
// The water mirror, for one of Horizon's own packs that reads it: the world as a
// camera mirrored about the water plane sees it, into a half-resolution target the
// material stage samples as `reflection`.
@@ -7064,6 +7077,7 @@ impl Renderer {
};
native.frame.fit_surface(&self.device, size);
}
+ laps.lap("r_mirror");
// One of Horizon's own packs with a material stage: terrain draws with its pipelines,
// which read the pack's frame at group 3.
let material = self
@@ -8054,6 +8068,7 @@ impl Renderer {
(&view_target, self.config.format.remove_srgb_suffix()),
);
}
+ laps.lap("r_passes");
// Under `HORIZON_FRAMEGEN_DEBUG=generated` a screenshot is the made frame.
let shown_texture = match &fg_frames {
Some((_, generated)) if fg_made && frame_gen::generated_only() => generated,
diff --git a/crates/horizon-client-render/src/spans.rs b/crates/horizon-client-render/src/spans.rs
index 7027b3fa1..0b0e8bf2f 100644
--- a/crates/horizon-client-render/src/spans.rs
+++ b/crates/horizon-client-render/src/spans.rs
@@ -46,6 +46,30 @@ pub fn time<T>(name: &'static str, f: impl FnOnce() -> T) -> T {
SPANS.with(|s| s.borrow_mut().push(Span { name, ms, cpu_ms }));
out
}
+/// Consecutive steps of one function timed as spans: each [`Laps::lap`] records the time since
+/// the previous one (or since [`laps`]) under its name. Nothing is read while spans are off.
+pub struct Laps(Option<(Instant, Option<Duration>)>);
+/// Start timing the steps of a function (see [`Laps`]).
+#[inline]
+pub fn laps() -> Laps {
+ Laps(enabled().then(|| (Instant::now(), thread_cpu())))
+}
+impl Laps {
+ /// Record the step that just ended under `name`, and start the next.
+ #[inline]
+ pub fn lap(&mut self, name: &'static str) {
+ let Some((started, cpu)) = &mut self.0 else {
+ return;
+ };
+ let (now, now_cpu) = (Instant::now(), thread_cpu());
+ let ms = (now - *started).as_secs_f32() * 1000.0;
+ let cpu_ms = now_cpu
+ .zip(*cpu)
+ .map_or(ms, |(end, start)| (end - start).as_secs_f32() * 1000.0);
+ SPANS.with(|s| s.borrow_mut().push(Span { name, ms, cpu_ms }));
+ (*started, *cpu) = (now, now_cpu);
+ }
+}
/// The CPU time this thread has used, where the platform tells it: a tick
/// with more wall time than CPU time waited (for a lock, or for a core on a
/// busy machine).
@@ -293,6 +317,25 @@ mod tests {
assert!(super::take().is_empty());
}
+ /// Laps record the steps between them while spans are on, and nothing while off.
+ #[test]
+ fn laps_time_consecutive_steps() {
+ let _ = super::take();
+ let mut off = super::laps();
+ off.lap("unseen");
+ super::enable(true);
+ let mut laps = super::laps();
+ std::thread::sleep(std::time::Duration::from_millis(2));
+ laps.lap("first");
+ laps.lap("second");
+ super::enable(false);
+ off.lap("still unseen");
+ let spans = super::take();
+ let names: Vec<_> = spans.iter().map(|s| s.name).collect();
+ assert_eq!(names, ["first", "second"]);
+ assert!(spans[0].ms >= 2.0);
+ }
+
/// The thread's CPU clock moves with work done on it, not with time
/// spent asleep.
#[cfg(any(unix, all(windows, target_arch = "x86_64")))]
diff --git a/crates/horizon-client/src/bin/horizon-ctl/commands.rs b/crates/horizon-client/src/bin/horizon-ctl/commands.rs
index 39318b25c..4abde6211 100644
--- a/crates/horizon-client/src/bin/horizon-ctl/commands.rs
+++ b/crates/horizon-client/src/bin/horizon-ctl/commands.rs
@@ -444,7 +444,7 @@ pub const COMMANDS: &[Cmd] = &[
"Add it to an MCP client as a stdio server: command horizon-ctl, args [\"mcp\"] (with --socket PATH first if needed). The screenshot tool returns the image.",
["horizon-ctl mcp"], &[], mcp: false, local: true),
cmd!("bench", Scripting, "bench SECONDS", "reset frame stats, wait, reply with the summary", "", ["horizon-ctl bench 10"], &[p("seconds", Ty::Num, "how long to measure")], mcp: true, local: false),
- cmd!("stats", Scripting, "stats [reset]", "frame-time summary since the last reset", "", ["horizon-ctl stats"], &[opt("reset", Ty::Bool, "start counting again")], mcp: true, local: false),
+ cmd!("stats", Scripting, "stats [reset] [raw]", "frame-time summary since the last reset", "", ["horizon-ctl stats"], &[opt("reset", Ty::Bool, "start counting again"), opt("raw", Ty::Bool, "every frame time too (frame_ms, cpu_ms, gpu_ms)")], mcp: true, local: false),
cmd!("gpu-passes", Scripting, "gpu-passes [on|off]", "time Horizon's own render passes on the GPU, shown in F3 and in stats and bench", "", ["horizon-ctl gpu-passes on"], &[opt("mode", Ty::Enum(&["on", "off"]), "on or off; without it, only reports")], mcp: false, local: false),
cmd!("fly", Scripting, "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]]", "fly the camera along a line, then reply with the frame summary",
"The reply's tick_ms and tick_ms_max are the world's smoothed tick time over the flight (the server thread's when single player runs on one). With raw, the reply also lists every frame time in milliseconds (frame_ms).",
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index 693a32a48..7b5c89a7f 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -10552,6 +10552,8 @@ impl Game<'_> {
alpha: f64,
mut out: Vec<Vertex>,
) -> Vec<Vertex> {
+ // Its steps as spans (HORIZON_SPIKES): each lap names the step that just ended.
+ let mut laps = horizon_client::spans::laps();
self.entity_spans.borrow_mut().clear();
self.entity_motion.borrow_mut().clear();
// LevelExtractor.extract: the transient blocks queued since the last frame.
@@ -10567,6 +10569,7 @@ impl Game<'_> {
} else {
self.yaw
};
+ laps.lap("eg_prep");
for m in &self.mobs {
// Blaze.isOnFire: a charged blaze burns.
let blazing = m.species() == horizon_client::mobs::Species::Blaze && m.extra.flag;
@@ -10611,6 +10614,7 @@ impl Game<'_> {
&mut out,
);
}
+ laps.lap("eg_fire_mobs");
for item in &self.dropped {
if item.fire_ticks > 0
&& !self
@@ -10635,6 +10639,7 @@ impl Game<'_> {
);
}
}
+ laps.lap("eg_fire_items");
for stand in &self.armor_stands {
if stand.fire_ticks > 0 && !stand.marker {
let scale = if stand.small { 0.5 } else { 1.0 };
@@ -10655,6 +10660,7 @@ impl Game<'_> {
);
}
}
+ laps.lap("eg_fire_stands");
// `ItemEntityRenderer`.
self.mark_entity(out.len(), "minecraft:item");
self.dropped_item_geometry(camera, alpha, &mut out);
@@ -10669,9 +10675,11 @@ impl Game<'_> {
self.shelf_geometry(camera, &mut out);
self.mark_entity(out.len(), "minecraft:ominous_item_spawner");
self.ominous_item_spawner_geometry(camera, alpha, &mut out);
+ laps.lap("eg_items_misc");
// Mobs and their projectiles (a span each).
self.mob_geometry(camera, alpha, &mut out);
self.mark_motion(out.len(), 0);
+ laps.lap("eg_mobs");
// In first person only a shader pack's shadow pass draws the player.
self.mark_player(out.len(), !self.own_body_in_view());
let player_start = out.len();
@@ -10688,6 +10696,7 @@ impl Game<'_> {
self.mark_entity(out.len(), "minecraft:evoker_fangs");
self.fangs_geometry(camera, alpha, &mut out);
self.block_item_display_geometry(camera, alpha, &mut out);
+ laps.lap("eg_players");
let mut see_through = std::mem::take(&mut self.see_through_vertices);
see_through.clear();
self.name_tag_geometry(camera, alpha, &mut out, &mut see_through);
@@ -10695,6 +10704,7 @@ impl Game<'_> {
self.debug_renderer_geometry(camera, &mut out);
self.text_display_geometry(camera, alpha, &mut out, &mut see_through);
self.see_through_vertices = see_through;
+ laps.lap("eg_name_tags");
// Entity shadows (EntityRenderer.extractShadow).
self.mark_translucent_entity(out.len(), "minecraft:entity_shadow");
// A native shader pack's sun shadows already fall under the entities in the Overworld:
@@ -10760,6 +10770,7 @@ impl Game<'_> {
);
}
}
+ laps.lap("eg_shadows");
// Block entities (BlockEntityRenderers): chests, shulker boxes, banners, skulls...
if let Some(r) = &self.renderer {
let lid = |p: [i32; 3]| self.chest_lid(p, alpha as f32);
@@ -10856,6 +10867,7 @@ impl Game<'_> {
.render_breaking(&scene, pos, state.0, stage, &mut out);
}
}
+ laps.lap("eg_block_entities");
// Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet.
self.mark_entity(out.len(), "minecraft:experience_orb");
if let Some(r) = self
@@ -10925,6 +10937,7 @@ impl Game<'_> {
}
}
}
+ laps.lap("eg_orbs");
// Falling blocks use their baked model, including non-cubic shapes.
self.mark_entity(out.len(), "minecraft:falling_block");
for f in &self.falling {
@@ -10989,6 +11002,7 @@ impl Game<'_> {
self.rocket_geometry(camera, alpha, &mut out);
self.mark_entity(out.len(), "minecraft:splash_potion");
self.thrown_potion_geometry(camera, alpha, &mut out);
+ laps.lap("eg_objects");
// Particles (ParticleEngine.extract): camera-facing quads.
self.mark_stage(out.len(), "PARTICLES");
let world = &self.world;
@@ -11000,6 +11014,7 @@ impl Game<'_> {
&|b| world.light(b[0], b[1], b[2]),
&mut out,
);
+ laps.lap("eg_particles");
// Breaking progress overlays (destroy_stage_0..9): ours and the other players'.
self.mark_stage(out.len(), "DESTROY");
for &(pos, stage) in &cracks {
@@ -11030,7 +11045,9 @@ impl Game<'_> {
}
}
}
+ laps.lap("eg_cracks");
self.finish_async_entity_culling();
+ laps.lap("eg_culling_finish");
out
}
diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs
index fe75e8890..b9bc723f2 100644
--- a/crates/horizon-client/src/game/control.rs
+++ b/crates/horizon-client/src/game/control.rs
@@ -36,7 +36,7 @@ const HELP: &[&str] = &[
"type TEXT type into the open chat box (key enter tap sends)",
"chat-log [N] the newest N chat messages (default 10)",
"options [PAGE] open the options (video sound controls keybinds mouse chat accessibility language font packs mods graphics graphics-advanced graphics-hdr)",
- "stats [reset] frame-time summary since the last reset",
+ "stats [reset] [raw] frame-time summary since the last reset (raw: every frame time too)",
"narration the narrator's status and the last messages it was asked to say",
"bench SECONDS reset stats, wait, then reply with the summary",
"fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]] fly the camera along a line at constant speed, then reply with the frame summary (raw: every frame time too)",
@@ -859,8 +859,13 @@ impl Game<'_> {
})))
}
"stats" => {
- let summary = self.summary_with_passes();
- if words.get(1) == Some(&"reset") {
+ let mut summary = self.summary_with_passes();
+ if words[1..].contains(&"raw") {
+ summary["frame_ms"] = self.frame_stats.frame_millis().into();
+ summary["cpu_ms"] = self.frame_stats.cpu_millis().into();
+ summary["gpu_ms"] = self.frame_stats.gpu_millis().into();
+ }
+ if words[1..].contains(&"reset") {
self.frame_stats.reset();
}
Ok(Some(summary))
diff --git a/docs/benchmark.md b/docs/benchmark.md
index 0eba8b00a..2b517a913 100644
--- a/docs/benchmark.md
+++ b/docs/benchmark.md
@@ -59,6 +59,24 @@ Options: `--distances 8,16`, `--sizes 1920x1080`, `--scenes village,ocean`, `--s
On Windows, run `python tools\perf_bench.py ...` the same way. Horizon's control endpoint there is a localhost TCP port, which the game writes to a `.json` file in the temporary folder. `--build` can point at an installed release (`%APPDATA%\horizon-launcher\versions\vX.Y.Z`, with `--resources` its `.local\horizon-client\26.3`), and the report then gives that release's version.
+## Frame pacing
+
+`tools/pacing_bench.py` measures smoothness rather than throughput: every frame of the sessions where players see
+hitches, a fast flight (64 blocks a second over new terrain), eight long teleports, trips to the Nether and back, and
+the inventory and pause menu opened and closed twenty times. For each it reports the median, p99 and p99.9 frame
+times, the slowest frame, the 1% and 0.1% lows and the frames over 33 ms. The game runs with `HORIZON_SPIKES`, so
+every slow frame also logs its timed spans (wall and thread CPU time): the report keeps the slowest ones next to the
+figures, which says whether a hitch was work (a span's CPU time) or waiting (the GPU, a lock, a file).
+`Renderer`'s frame and `entity_geometry` time their steps as spans too (`spans::laps`).
+
+```sh
+python3 tools/pacing_bench.py --build target/fast --label main --distances 32
+python3 tools/pacing_bench.py --compare main mybranch
+```
+
+`--size 320x180` keeps a software renderer (Mesa's lavapipe on a machine with no GPU) from hiding the CPU side; there
+only the spans' CPU times mean anything.
+
## Results
Saved runs go to `benchmarks/perf/`; `--table` prints them as Markdown.
diff --git a/docs/horizon-ctl-commands.md b/docs/horizon-ctl-commands.md
index 2bcfde074..8c4c2248d 100644
--- a/docs/horizon-ctl-commands.md
+++ b/docs/horizon-ctl-commands.md
@@ -137,6 +137,6 @@ Every command `horizon-ctl` takes, its MCP tool in `horizon-ctl mcp` (the launch
| `sleep SECONDS` | CLI only | Wait (in scripts) | none |
| `mcp` | CLI only | Serve the Model Context Protocol on stdin/stdout, one tool per command | none |
| `bench SECONDS` | `bench` | Reset frame stats, wait, reply with the summary | `seconds` (number, required): how long to measure |
-| `stats [reset]` | `stats` | Frame-time summary since the last reset | `reset` (boolean): start counting again |
+| `stats [reset] [raw]` | `stats` | Frame-time summary since the last reset | `reset` (boolean): start counting again<br>`raw` (boolean): every frame time too (frame_ms, cpu_ms, gpu_ms) |
| `gpu-passes [on\|off]` | CLI only | Time Horizon's own render passes on the GPU, shown in F3 and in stats and bench | `mode` (on, off): on or off; without it, only reports |
| `fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]]` | CLI only | Fly the camera along a line, then reply with the frame summary | none |
diff --git a/tests/test_pacing_bench.py b/tests/test_pacing_bench.py
new file mode 100644
index 000000000..a5b433d9e
--- /dev/null
+++ b/tests/test_pacing_bench.py
@@ -0,0 +1,28 @@
+import unittest
+
+from tools.pacing_bench import stats
+
+
+class StatsTests(unittest.TestCase):
+ def test_lows_percentiles_and_hitch_counts(self):
+ # 998 frames of 5 ms, one of 40 ms and one of 100 ms.
+ frames = [5.0] * 998 + [40.0, 100.0]
+ s = stats(frames)
+ self.assertEqual(s["frames"], 1000)
+ self.assertEqual(s["p50_ms"], 5.0)
+ self.assertEqual(s["p99_ms"], 5.0)
+ self.assertEqual(s["p999_ms"], 40.0)
+ self.assertEqual(s["max_ms"], 100.0)
+ # The slowest 1% (10 frames): 8 x 5 + 40 + 100 = 180 ms, 18 ms each.
+ self.assertAlmostEqual(s["low_1pct_fps"], round(1000 / 18.0, 1))
+ # The slowest 0.1% is the single 100 ms frame.
+ self.assertEqual(s["low_01pct_fps"], 10.0)
+ self.assertEqual(s["over_33ms"], 2)
+ self.assertEqual(s["over_2x_median"], 2)
+
+ def test_no_frames(self):
+ self.assertEqual(stats([]), {"frames": 0})
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/pacing_bench.py b/tools/pacing_bench.py
new file mode 100644
index 000000000..3088a084e
--- /dev/null
+++ b/tools/pacing_bench.py
@@ -0,0 +1,239 @@
+#!/usr/bin/env python3
+"""Frame pacing benchmark: every frame of long stutter-prone sessions, and what the slow ones did.
+
+perf_bench.py measures throughput on short flights; this measures smoothness (1% and 0.1% lows,
+p99/p99.9, the worst frame, frames over 33 ms) in the situations where players see hitches:
+
+ fly16 the village flight of perf_bench, 16 blocks/s, 12 s
+ fly64 a 1,920-block straight line at 64 blocks/s (30 s), new terrain all the way
+ teleport 8 teleports of 1,500-3,000 blocks, 5 s recorded after each
+ nether the overworld -> Nether -> overworld (/execute in ... run tp), 8 s recorded after each
+ inventory the inventory and the pause menu opened and closed 20 times each
+
+One game per render distance, from a fresh world (seed 1234, creative), driven over horizon-ctl.
+The game runs with HORIZON_SPIKES so each slow frame logs its timed spans; the report keeps the
+slowest frames' span lines next to each scenario's figures.
+
+ python3 tools/pacing_bench.py --build target/fast --label main --distances 32
+ python3 tools/pacing_bench.py --compare main mybranch
+
+Results: .local/pacing-bench/<label>-rd<N>.json. Use alternated A/B runs on a loaded machine.
+"""
+import argparse
+import json
+import math
+import os
+import re
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+import lab # noqa: E402
+import perf_bench as pb # noqa: E402
+
+WORK = lab.ROOT / ".local/pacing-bench"
+SCENARIOS = ["fly16", "fly64", "teleport", "nether", "inventory"]
+SPIKE_RE = re.compile(r"slow frame ([\d.]+) ms")
+
+
+def stats(frame_ms):
+ """p50/p99/p99.9/max, 1% and 0.1% lows (average of the slowest 1%/0.1%, as FPS), frames over 33 ms
+ and over twice the median."""
+ values = sorted(frame_ms)
+ n = len(values)
+ if not n:
+ return {"frames": 0}
+ pct = lambda p: values[min(n, max(1, math.ceil(n * p))) - 1]
+ low = lambda per: 1000.0 / (sum(values[n - math.ceil(n / per):]) / math.ceil(n / per))
+ median = pct(0.5)
+ return {
+ "frames": n,
+ "seconds": round(sum(values) / 1000.0, 2),
+ "avg_fps": round(n * 1000.0 / sum(values), 1),
+ "p50_ms": round(median, 2),
+ "p99_ms": round(pct(0.99), 2),
+ "p999_ms": round(pct(0.999), 2),
+ "max_ms": round(values[-1], 2),
+ "low_1pct_fps": round(low(100), 1),
+ "low_01pct_fps": round(low(1000), 1),
+ "over_33ms": sum(v > 33.34 for v in values),
+ "over_2x_median": sum(v > 2 * median for v in values),
+ }
+
+
+def record(control, action, seconds):
+ """Resets the frame stats, runs action(), waits `seconds` and returns every frame time since."""
+ control("stats reset")
+ action()
+ time.sleep(seconds)
+ reply = control("stats raw reset")
+ return reply.get("frame_ms") or [], reply.get("cpu_ms") or []
+
+
+def scenario(name, control, distance):
+ frames, cpu = [], []
+
+ def add(result):
+ frames.extend(result[0])
+ cpu.extend(result[1])
+
+ if name == "fly16":
+ _, start, end, pitch = pb.SCENES[0]
+ control("tp {} {} {}".format(*start))
+ control("fly {0} {1} {2} {0} {1} {2} 0.1 {3}".format(*start, pitch))
+ pb.wait_loaded(control, lambda p: True, 300, pb.view_chunks(distance))
+ time.sleep(2)
+ reply = control("fly {} {} {} {} {} {} 12 {} raw".format(*start, *end, pitch))
+ add((reply.get("frame_ms") or [], reply.get("cpu_ms") or []))
+ elif name == "fly64":
+ start, end = (3000.0, 140.0, -3000.0), (3000.0, 140.0, -1080.0)
+ control("tp {} {} {}".format(*start))
+ control("fly {0} {1} {2} {0} {1} {2} 0.1 20".format(*start))
+ pb.wait_loaded(control, lambda p: True, 300, pb.view_chunks(distance))
+ time.sleep(2)
+ reply = control("fly {} {} {} {} {} {} 30 20 raw".format(*start, *end))
+ add((reply.get("frame_ms") or [], reply.get("cpu_ms") or []))
+ elif name == "teleport":
+ targets = [(-3000, 150, 2000), (1500, 150, 2500), (4000, 150, -500), (0, 150, -3500),
+ (-2500, 150, -1500), (2500, 150, 1000), (-500, 150, 4000), (3500, 150, 3500)]
+ for x, y, z in targets:
+ add(record(control, lambda: (control(f"tp {x} {y} {z}"),
+ control(f"fly {x} {y} {z} {x} {y} {z} 0.1 10")), 5))
+ elif name == "nether":
+ for dim, (x, y, z) in [("the_nether", (100, 100, 100)), ("overworld", (800, 150, 800)),
+ ("the_nether", (-300, 100, 200)), ("overworld", (-2400, 150, 1600))]:
+ add(record(control, lambda: control(f"command execute in minecraft:{dim} run tp @s {x} {y} {z}"), 8))
+ elif name == "inventory":
+ def spam():
+ for _ in range(20):
+ control("open-inventory")
+ time.sleep(0.15)
+ control("key esc tap")
+ time.sleep(0.15)
+ for _ in range(20):
+ control("pause")
+ time.sleep(0.15)
+ control("resume")
+ time.sleep(0.15)
+ add(record(control, spam, 0.5))
+ return frames, cpu
+
+
+def run(args, distance):
+ game_dir = WORK / f"game-{args.label}-rd{distance}"
+ import shutil
+ shutil.rmtree(game_dir, ignore_errors=True)
+ pb.write_options(game_dir, distance)
+ sock = Path("/tmp") / f"horizon-pacing-{os.getpid()}.sock"
+ sock.unlink(missing_ok=True)
+ client = Path(args.build).resolve() / "horizon-client"
+ command = [str(client), "--resources", str(Path(args.resources).resolve()), "--control-socket", str(sock),
+ "--no-pause", "--weather", "clear", "--time", "6000"]
+ if args.size:
+ width, _, height = args.size.partition("x")
+ command += ["--width", width, "--height", height]
+ if args.offscreen:
+ command.append("--offscreen")
+ env = lab.game_env(HORIZON_TELEMETRY_URL="off", HORIZON_SPIKES=str(args.spike_ms))
+ for kv in args.env:
+ k, _, v = kv.partition("=")
+ env[k] = v
+ log_path = WORK / f"{args.label}-rd{distance}.log"
+ result = {"label": args.label, "distance": distance, "load_before": pb.load_average(), "scenarios": {}}
+ with log_path.open("w") as log:
+ proc = subprocess.Popen(command, cwd=game_dir, env=env, stdout=log, stderr=subprocess.STDOUT)
+ control = pb.Control(sock)
+ try:
+ pb.poll(control, lambda s: s.get("screen") == "title" and s.get("renderer"), 300)
+ control(f"open {pb.WORLD} {pb.SEED} creative")
+ pb.wait_loaded(control, lambda p: True, args.timeout, pb.view_chunks(distance))
+ for name in args.scenarios.split(","):
+ mark = log_path.stat().st_size
+ frames, cpu = scenario(name, control, distance)
+ log.flush()
+ with log_path.open(errors="replace") as f:
+ f.seek(mark)
+ spikes = [line.strip() for line in f if "slow frame" in line]
+ spikes.sort(key=lambda line: -float(SPIKE_RE.search(line).group(1)))
+ entry = stats(frames)
+ entry["cpu"] = stats(cpu)
+ entry["slowest_spans"] = spikes[:12]
+ entry["spike_lines"] = len(spikes)
+ entry["frame_ms"] = [round(v, 2) for v in frames]
+ result["scenarios"][name] = entry
+ print(f"rd{distance} {name}: " + ", ".join(f"{k} {v}" for k, v in entry.items()
+ if k not in ("cpu", "slowest_spans", "frame_ms")), flush=True)
+ finally:
+ try:
+ control("quit", timeout=60)
+ except (OSError, ValueError, RuntimeError):
+ pass
+ pb.stop(proc)
+ sock.unlink(missing_ok=True)
+ shutil.rmtree(game_dir, ignore_errors=True)
+ result["load_after"] = pb.load_average()
+ return result
+
+
+COLUMNS = [("p50_ms", "p50"), ("p99_ms", "p99"), ("p999_ms", "p99.9"), ("max_ms", "max"),
+ ("low_1pct_fps", "1% low"), ("low_01pct_fps", "0.1% low"), ("over_33ms", ">33 ms")]
+
+
+def compare(labels):
+ """Markdown table per scenario: the median over a label's runs (files <label>-rd<N>*.json)."""
+ runs = {}
+ for label in labels:
+ for path in sorted(WORK.glob(f"{label}-rd*.json")):
+ data = json.loads(path.read_text())
+ if data["label"] != label:
+ continue
+ runs.setdefault((data["distance"], label), []).append(data)
+ for distance in sorted({d for d, _ in runs}):
+ names = [n for n in SCENARIOS if any(n in r["scenarios"] for (d, _), rs in runs.items() if d == distance
+ for r in rs)]
+ for name in names:
+ print(f"\n**RD {distance}, {name}** (median of n runs)\n")
+ print("| build | n | " + " | ".join(c for _, c in COLUMNS) + " |")
+ print("|---|---|" + "---|" * len(COLUMNS))
+ for label in labels:
+ entries = [r["scenarios"][name] for r in runs.get((distance, label), []) if name in r["scenarios"]]
+ if not entries:
+ continue
+ cells = []
+ for key, _ in COLUMNS:
+ values = sorted(e.get(key, 0) for e in entries)
+ cells.append(f"{values[len(values) // 2]:g}")
+ print(f"| {label} | {len(entries)} | " + " | ".join(cells) + " |")
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--label", default="horizon")
+ parser.add_argument("--build", default=str(lab.ROOT / "target/fast"))
+ parser.add_argument("--resources", default=str(lab.ROOT / ".local/horizon-client/26.3"))
+ parser.add_argument("--distances", default="32")
+ parser.add_argument("--scenarios", default=",".join(SCENARIOS))
+ parser.add_argument("--timeout", type=float, default=600)
+ parser.add_argument("--spike-ms", type=float, default=20.0, help="HORIZON_SPIKES threshold (CPU ms)")
+ parser.add_argument("--offscreen", action="store_true")
+ parser.add_argument("--size", help="window size WxH (default the game's 1280x720); a small one keeps a software "
+ "renderer (lavapipe) from hiding the CPU side")
+ parser.add_argument("--env", action="append", default=[], help="KEY=VALUE for the game")
+ parser.add_argument("--run", type=int, default=0, help="run number, kept in the file name")
+ parser.add_argument("--compare", nargs="+", metavar="LABEL")
+ args = parser.parse_args()
+ if args.compare:
+ compare(args.compare)
+ return
+ WORK.mkdir(parents=True, exist_ok=True)
+ for distance in map(int, args.distances.split(",")):
+ result = run(args, distance)
+ out = WORK / f"{args.label}-rd{distance}-{args.run}.json"
+ out.write_text(json.dumps(result))
+ print(f"wrote {out}")
+
+
+if __name__ == "__main__":
+ main()