From d2cedc28130f941b32cafc65a876c2bb0ccb2fa1 Mon Sep 17 00:00:00 2001 From: Michael McCrimmons Date: Fri, 27 Nov 2026 16:10:57 -0600 Subject: [PATCH] diag(gpu): GPU time per pipeline without timestamps (VICTORY_GPU_TIMING_CUTS) D3D12 timestamps all read 0 under D3DMetal, so VICTORY_GPU_TIMING times whole host lists on a Mac and cannot say which pipeline of a list took the time. With VICTORY_GPU_TIMING_CUTS a title list goes on in a fresh host list around the draws and dispatches of a few pipelines at a time (as it does after a wait or for a clamp cut), so each such list runs one pipeline and its wall time is that pipeline's; everything else stays together and the frame keeps its shape. A list of shader hashes takes those pipelines; 'sweep' takes 16 at a time of the pipelines the title is drawing with, the next ones after every frame-rate line. Each frame-rate line is followed by the pipelines ranked by their time above the lists' floor, per frame they had lists in. Diagnostics builds only; off, nothing changes. --- README.md | 2 + crates/victory-gpu/src/draw.rs | 6 + crates/victory-gpu/src/host.rs | 171 +++++++++- crates/victory-gpu/src/lib.rs | 3 + crates/victory-gpu/src/list.rs | 74 +++++ crates/victory-gpu/src/timing_cuts.rs | 443 ++++++++++++++++++++++++++ 6 files changed, 698 insertions(+), 1 deletion(-) create mode 100644 crates/victory-gpu/src/timing_cuts.rs diff --git a/README.md b/README.md index c0a2b3393..3bde2ebd0 100644 --- a/README.md +++ b/README.md @@ -158,6 +158,7 @@ A diagnostics build also logs one bounded line per submission that refreshes tit | `VICTORY_STACKS_FILE=` | Writes those dumps to a file without taking locks, for freezes. | | `VICTORY_SKIP_TITLE_INT3=,...` | Steps over the game's own `int3` asserts at those hex RVAs and logs each one. Every other assert still stops the run. | | `VICTORY_GPU_TIMING=1` | Submits and times each GPU list on its own. | +| `VICTORY_GPU_TIMING_CUTS=sweep` | GPU time per pipeline on a Mac, where GPU timestamps read 0: a few pipelines at a time get host lists of their own, timed by the clock, round all of them in a few minutes. `=,...` times the pipelines of those shaders only. Diagnostics builds. | ### Every variable @@ -184,6 +185,7 @@ The on/off switches below (`...=1`) are off when unset or set to `0`. | `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | | `VICTORY_SKIP_PIPELINES=,...` | skip host pipeline creation and omit draws and dispatches, including indirect ones, when the pipeline contains a listed 16-digit shader hash | | `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands; a device removal names the list it happened in and lists all its commands | +| `VICTORY_GPU_TIMING_CUTS=sweep` | GPU time per pipeline without GPU timestamps (D3DMetal reads them all as 0): turns `VICTORY_GPU_TIMING` on, and a title list goes on in a fresh host list around the draws and dispatches of a few pipelines at a time, so each such list runs one pipeline and its wall time is that pipeline's; everything else stays together and the frame keeps its shape. `sweep` (or `sweep:`, 16 by default) takes `n` at a time of the pipelines the title is drawing with, in the order it first drew with them, and moves on after every frame-rate line, so standing still for a few minutes times every pipeline of the scene; `,...` (16-digit shader hashes) takes the pipelines with a listed shader, for as long as the run lasts. Every frame-rate line is followed by `GPU wall time by pipeline`: lists and ms a frame, the lists' floor (tenth percentile, what an empty list costs), how far the sweep is, then the pipelines, each per frame it had lists in: ms, ms above the floor, lists, commands, and those frames | | `VICTORY_TRACE_SHADERS=,...` | with `VICTORY_D3D12_DRED`, every draw and dispatch of a listed shader logged with what it binds (user data, heap slots, root views and their first dwords; the first 500, and all of them in listed capture frames); the records of its indirect executions are read back and logged in every frame (records with work, the first four, the frame) | | `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) | | `VICTORY_PIPELINE_LOG=` | a line per title pipeline created (key, shaders, state), first used, and made or loaded (library name); `translate --cache --pipelines` writes the last kind too | diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index ae0ba7aab..c7e6185ee 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1750,6 +1750,12 @@ impl State { } } + /// The title pipeline the next draw or dispatch runs (null: none set). + #[cfg(feature = "diagnostics")] + pub(crate) fn title_pipeline(&self) -> usize { + self.pipeline + } + /// Flushes any pending RTV probes recorded during `VICTORY_HDR_PROBE`. pub(crate) fn flush_hdr_probe(&mut self, list: &HostList) { let Some((targets, shaders)) = self.hdr_rtvs.take() else { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4c8e1bfac..1925b596f 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1565,6 +1565,10 @@ pub(crate) struct HostList { /// and at the end, and where they are read back. #[cfg(feature = "diagnostics")] stamps: OnceLock>, + /// With `VICTORY_GPU_TIMING_CUTS`: the one kind and pipeline of the + /// list's draws or dispatches, once it has any (`crate::timing_cuts`). + #[cfg(feature = "diagnostics")] + timed: Mutex>, } // SAFETY: D3D12 objects are free-threaded; a host list is recorded by the @@ -1603,7 +1607,109 @@ pub(crate) fn dred_on() -> bool { #[cfg(feature = "diagnostics")] fn timing() -> bool { static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| crate::switch::on("VICTORY_GPU_TIMING")) + *ON.get_or_init(|| crate::switch::on("VICTORY_GPU_TIMING") || timing_cuts_on()) +} + +/// Whether a few pipelines at a time get host lists of their own, so that +/// a timed list of theirs runs one pipeline and its wall time is that +/// pipeline's (`VICTORY_GPU_TIMING_CUTS`, diagnostics builds; turns the +/// timing on): GPU time per pipeline where timestamps do not advance, as +/// under D3DMetal. See `crate::timing_cuts`. +#[cfg(feature = "diagnostics")] +pub(crate) fn timing_cuts_on() -> bool { + *timing_cuts() != crate::timing_cuts::Mode::Off +} + +#[cfg(feature = "diagnostics")] +fn timing_cuts() -> &'static crate::timing_cuts::Mode { + static MODE: OnceLock = OnceLock::new(); + MODE.get_or_init(|| { + let mode = crate::timing_cuts::mode_of(std::env::var("VICTORY_GPU_TIMING_CUTS").ok().as_deref()); + if mode != crate::timing_cuts::Mode::Off { + tracing::info!( + ?mode, + "VICTORY_GPU_TIMING_CUTS: host lists of their own for a few pipelines at a time, each list \ + run and timed on its own" + ); + } + mode + }) +} + +/// A sweep's pipelines and where it is (`VICTORY_GPU_TIMING_CUTS=sweep`). +#[cfg(feature = "diagnostics")] +static SWEEP: Mutex> = Mutex::new(None); + +/// Whether the title pipeline `this` gets host lists of its own now: it +/// has a listed shader (remembered per pipeline, which the title makes +/// once and keeps), or the sweep is at it. +#[cfg(feature = "diagnostics")] +pub(crate) fn timing_cut_own(this: usize) -> bool { + use crate::timing_cuts::Mode; + if this == 0 { + return false; + } + match timing_cuts() { + Mode::Off => false, + Mode::Sweep(_) => SWEEP + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get_or_insert_with(Default::default) + .times(this), + Mode::Listed(listed) => { + static SEEN: Mutex>> = Mutex::new(None); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + *seen + .get_or_insert_with(Default::default) + .entry(this) + .or_insert_with(|| { + crate::timing_cuts::lists( + listed, + &crate::pipeline::shaders_of(this as crate::object::This), + ) + }) + } + } +} + +/// The timed lists' wall time by pipeline since the last frame-rate line +/// (`VICTORY_GPU_TIMING_CUTS`). +#[cfg(feature = "diagnostics")] +static GPU_WALLS: Mutex> = Mutex::new(None); + +/// Logs [`GPU_WALLS`] over `frames` frames: the 40 pipelines that cost most +/// above the lists' floor, each per frame it had lists in. +#[cfg(feature = "diagnostics")] +fn log_gpu_walls(frames: f64) { + let Some(walls) = GPU_WALLS.lock().unwrap_or_else(|e| e.into_inner()).take() else { + return; + }; + let (lists, ms, floor, rows) = walls.report(frames); + let sweep = match timing_cuts() { + crate::timing_cuts::Mode::Sweep(n) => { + let mut sweep = SWEEP.lock().unwrap_or_else(|e| e.into_inner()); + let (now, live) = sweep.get_or_insert_with(Default::default).advance(*n); + format!("; the sweep goes on with {now} of the {live} pipelines drawn with") + } + _ => String::new(), + }; + tracing::info!( + "GPU wall time by pipeline: {lists:.1} timed lists/frame, {ms:.1} ms/frame; a list's floor {floor:.3} ms \ + (tenth percentile); {} lines{sweep}", + rows.len() + ); + for r in rows.iter().take(40) { + tracing::info!( + " GPU wall {:.2} ms ({:.2} above the floor) in {:.1} lists, {:.1} commands a frame, \ + in {} frames: {}", + r.ms, + r.above, + r.lists, + r.commands, + r.frames, + r.label + ); + } } /// On D3DMetal, a separate native queue call before a deferred UAV-to-SRV @@ -2123,6 +2229,8 @@ impl HostGpu for Host { targets: Mutex::default(), #[cfg(feature = "diagnostics")] stamps: OnceLock::new(), + #[cfg(feature = "diagnostics")] + timed: Mutex::default(), }) } } @@ -2303,6 +2411,19 @@ impl Host { ); } #[cfg(feature = "diagnostics")] + if gpu_timing && timing_cuts_on() { + let timed = runs[i].timed.lock().unwrap_or_else(|e| e.into_inner()); + GPU_WALLS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get_or_insert_with(Default::default) + .add( + started.elapsed().as_secs_f64() * 1e3, + timed.as_ref(), + crate::queue::presented(), + ); + } + #[cfg(feature = "diagnostics")] if groups.len() > 1 && started.elapsed() > std::time::Duration::from_millis(50) { // SAFETY: a plain query. let frequency = unsafe { queue.GetTimestampFrequency() }.unwrap_or(1); @@ -3335,6 +3456,8 @@ impl HostList { self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear(); #[cfg(feature = "diagnostics")] self.targets.lock().unwrap_or_else(|e| e.into_inner()).clear(); + #[cfg(feature = "diagnostics")] + self.timed.lock().unwrap_or_else(|e| e.into_inner()).take(); self.trim_scratch(); self.reset_hoisted_clamps(); self.marked.store(false, Ordering::Relaxed); @@ -3909,6 +4032,51 @@ impl HostList { } } + /// With `VICTORY_GPU_TIMING_CUTS`: whether a draw or dispatch of `key` + /// (`crate::timing_cuts::key`) belongs in a host list after this one, + /// which runs another kind or pipeline. + #[cfg(feature = "diagnostics")] + pub(crate) fn timed_cuts(&self, (key, compute): (usize, bool)) -> bool { + let timed = self.timed.lock().unwrap_or_else(|e| e.into_inner()); + crate::timing_cuts::cuts(timed.as_ref(), key, compute) + } + + /// Counts a draw or dispatch of `key` about to be recorded into the + /// list, whose kind and pipeline it gives the list if it is the first + /// (`name`: the pipeline's shaders). + #[cfg(feature = "diagnostics")] + pub(crate) fn timed_command( + &self, + (key, compute): (usize, bool), + name: impl FnOnce() -> String, + ) { + let mut timed = self.timed.lock().unwrap_or_else(|e| e.into_inner()); + match timed.as_mut() { + Some(t) => t.commands += 1, + None => { + *timed = Some(crate::timing_cuts::Timed { + key, + compute, + commands: 1, + name: name(), + }) + } + } + } + + /// Takes back the last [`HostList::timed_command`]: its command went + /// into the next host list after all (a cut for an indirect clamp). + #[cfg(feature = "diagnostics")] + pub(crate) fn timed_command_moved(&self) { + let mut timed = self.timed.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(t) = timed.as_mut() { + t.commands = t.commands.saturating_sub(1); + if t.commands == 0 { + *timed = None; + } + } + } + /// Notes a texture the list renders to or writes, in a listed frame. #[cfg(feature = "diagnostics")] pub(crate) fn note_target(&self, resource: usize, by: &str) { @@ -5918,6 +6086,7 @@ impl Meter { let drops = crate::pipeline::take_drops(); crate::frame::log(); log_gpu_times(report_frames); + log_gpu_walls(report_frames); crate::copystat::log(report_frames); crate::bindless::log(report_frames); crate::heap_worker::log(report_frames); diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index c7e8357b3..da53dd0e9 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -104,6 +104,9 @@ mod tdr; mod texback; #[cfg(windows)] mod texture; +// Plain std, so its tests run everywhere. +#[cfg(any(windows, test))] +mod timing_cuts; #[cfg(windows)] mod twin; #[cfg(windows)] diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 561576119..a2b856ac1 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -255,6 +255,71 @@ fn cut_for_clamp(this: This) -> bool { true } +/// With `VICTORY_GPU_TIMING_CUTS` (diagnostics builds), before a draw or +/// dispatch (`compute`) is recorded: the title list goes on in a new host +/// list where a pipeline that gets lists of its own starts or ends, as +/// [`cut_for_clamp`] moves it on, so that such a timed host list runs one +/// pipeline and its wall time is that pipeline's (`crate::timing_cuts`). +/// The command is counted in the list it goes into. Without a new host +/// list it stays in the current one, under that list's first pipeline. +#[cfg(all(windows, feature = "diagnostics"))] +fn cut_for_timing(this: This, compute: bool) { + if !crate::host::timing_cuts_on() { + return; + } + let Some(current) = host_list(this) else { + return; + }; + // SAFETY: the title passes one of our lists. + let list = unsafe { &*this.cast::() }; + let pipeline = list + .state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .title_pipeline(); + let key = crate::timing_cuts::key(pipeline, compute, crate::host::timing_cut_own(pipeline)); + let mut into = current; + if current.timed_cuts(key) + && let Some(next) = next_segment(this) + { + let mut state = list.state.lock().unwrap_or_else(|e| e.into_inner()); + state.flush_hdr_probe(current); + current.close(); + state.cut(next); + into = next; + } + into.timed_command(key, || crate::pipeline::shaders_of(pipeline as This)); +} + +#[cfg(all(windows, not(feature = "diagnostics")))] +fn cut_for_timing(_: This, _: bool) {} + +/// After [`cut_for_clamp`] moved an indirect execution that +/// [`cut_for_timing`] had counted in `previous` on to a new host list: it +/// is counted there instead. +#[cfg(all(windows, feature = "diagnostics"))] +fn retime_after_clamp_cut(this: This, previous: Option<&crate::host::HostList>, compute: bool) { + let (Some(previous), Some(current)) = (previous, host_list(this)) else { + return; + }; + if !crate::host::timing_cuts_on() || std::ptr::eq(previous, current) { + return; + } + // SAFETY: the title passes one of our lists. + let list = unsafe { &*this.cast::() }; + let pipeline = list + .state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .title_pipeline(); + previous.timed_command_moved(); + let key = crate::timing_cuts::key(pipeline, compute, crate::host::timing_cut_own(pipeline)); + current.timed_command(key, || crate::pipeline::shaders_of(pipeline as This)); +} + +#[cfg(all(windows, not(feature = "diagnostics")))] +fn retime_after_clamp_cut(_: This, _: Option<&crate::host::HostList>, _: bool) {} + /// Moves a title list's recording on to its next host list (made, or one /// it held since an earlier recording, reset then): that host list. #[cfg(windows)] @@ -1747,17 +1812,20 @@ mod state { first_instance: u32, ) { super::count_draw(); + super::cut_for_timing(this, false); with_state(this, |list, s| { s.draw(list, vertices, instances, first, first_instance) }); } pub(super) extern "system" fn dispatch(this: This, x: u32, y: u32, z: u32) { super::count_dispatch(); + super::cut_for_timing(this, true); with_state(this, |list, s| s.dispatch(list, x, y, z)); } /// `DispatchX` with its console flags (`State::dispatch_x`). pub(super) fn dispatch_x(this: This, x: u32, y: u32, z: u32, flags: u32) { super::count_dispatch(); + super::cut_for_timing(this, true); with_state(this, |list, s| s.dispatch_x(list, x, y, z, flags)); } /// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh @@ -1768,6 +1836,7 @@ mod state { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| tracing::warn!(x, y, z, "a mesh dispatch with y or z groups")); } + super::cut_for_timing(this, false); with_state(this, |list, s| s.dispatch_mesh(list, x)); } /// `DispatchMeshX(x, flags, indirect arguments, payload)`. @@ -1786,6 +1855,7 @@ mod state { ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped")); return; } + super::cut_for_timing(this, false); with_state(this, |list, s| s.dispatch_mesh(list, x)); } pub(super) extern "system" fn draw_indexed( @@ -1797,6 +1867,7 @@ mod state { first_instance: u32, ) { super::count_draw(); + super::cut_for_timing(this, false); with_state(this, |list, s| { s.draw_indexed(list, indices, instances, first, base, first_instance) }); @@ -1882,12 +1953,15 @@ extern "system" fn execute_indirect( }; use crate::draw::Indirect; let mut outcome = Indirect::NotRun; + cut_for_timing(this, kind == DISPATCH); with_state(this, |list, s| { outcome = s.execute_indirect(list, (kind, stride, max), address, counter, true); }); if outcome == Indirect::CutFirst { // Clamped inline in the same host list if no new one can be had. + let previous = host_list(this); cut_for_clamp(this); + retime_after_clamp_cut(this, previous, kind == DISPATCH); with_state(this, |list, s| { outcome = s.execute_indirect(list, (kind, stride, max), address, counter, false); }); diff --git a/crates/victory-gpu/src/timing_cuts.rs b/crates/victory-gpu/src/timing_cuts.rs new file mode 100644 index 000000000..c2480ea92 --- /dev/null +++ b/crates/victory-gpu/src/timing_cuts.rs @@ -0,0 +1,443 @@ +//! `VICTORY_GPU_TIMING_CUTS`: GPU time per pipeline from wall time alone, +//! for hosts whose D3D12 timestamps do not advance. +//! +//! `VICTORY_GPU_TIMING` runs each host list on its own and waits for it, so +//! a list's wall time is its GPU time; which command of the list took it +//! comes from timestamp queries, and under D3DMetal those all read 0. With +//! the cuts on, a title list goes on in a fresh host list (a segment, as +//! after a wait: `crate::list`) wherever the pipeline changes, so every host +//! list runs one pipeline and its wall time is that pipeline's. +//! +//! Two modes, and both leave nearly all of the frame as it is: only a few +//! pipelines at a time get lists of their own, everything else stays +//! together. A list of shader hashes (`,`): the pipelines with a +//! listed shader. `sweep` (or `sweep:`, 16 by default): `n` pipelines at +//! a time of those the title drew with since the last frame-rate line, in +//! the order it first drew with them, the next `n` after every such line, +//! round and round, so that a few minutes in one place time every pipeline +//! of the scene, draws included. A pipeline's figures are per frame it had +//! lists in, as its turn starts and ends inside a report's frames. +//! +//! Cutting at every change of pipeline instead was tried and is not here: a +//! world frame of Grand Theft Auto VI became about 2,000 host lists, video +//! memory grew by 12 GB, single lists stalled for seconds, and a pipeline +//! that costs 0.7 ms a frame listed alone was blamed for 2 to 15 s. The +//! report gives the lists' floor (the tenth percentile of all lists' wall +//! time) and each pipeline's time above it. +//! +//! Plain std: the decisions and the sums, tested everywhere. The host list +//! holds a [`Timed`], `crate::list` cuts, `crate::host` times and logs. +#![allow(dead_code)] + +use std::collections::HashMap; + +/// What the switch asks for. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Mode { + Off, + /// Lists of their own for the pipelines with one of these shader + /// hashes (lower case). + Listed(Vec), + /// Lists of their own for this many pipelines at a time, the next ones + /// after every report. + Sweep(usize), +} + +/// Pipelines a sweep times at once, unless the switch says. +pub(crate) const SWEEP: usize = 16; + +/// The mode a value of `VICTORY_GPU_TIMING_CUTS` selects: off when unset or +/// `0` (as every switch); a comma-separated list of 16-digit shader hashes +/// for those pipelines; `sweep:` for `n` pipelines at a time; anything +/// else that is on, a sweep of [`SWEEP`]. +pub(crate) fn mode_of(value: Option<&str>) -> Mode { + let Some(value) = value.map(str::trim) else { + return Mode::Off; + }; + if value == "0" { + return Mode::Off; + } + let hashes: Vec = value + .split(',') + .map(|h| h.trim().to_ascii_lowercase()) + .filter(|h| !h.is_empty()) + .collect(); + let hash = |h: &String| h.len() == 16 && h.bytes().all(|b| b.is_ascii_hexdigit()); + if !hashes.is_empty() && hashes.iter().all(hash) { + return Mode::Listed(hashes); + } + let n = value + .to_ascii_lowercase() + .strip_prefix("sweep:") + .and_then(|n| n.trim().parse().ok()) + .filter(|&n| n > 0); + Mode::Sweep(n.unwrap_or(SWEEP)) +} + +/// Whether a pipeline named by its shaders (`[compute 0123..]`) has one of +/// the `listed` hashes. +pub(crate) fn lists(listed: &[String], shaders: &str) -> bool { + listed.iter().any(|h| shaders.contains(h.as_str())) +} + +/// The pipelines a sweep has seen, in the order the title first drew with +/// them, the ones it times now, and where it goes on. +#[derive(Default)] +pub(crate) struct Sweep { + /// Each pipeline's place in the order. + order: std::collections::HashMap, + /// The pipelines by place. + seen: Vec, + /// The places drawn with since the last report. + live: std::collections::BTreeSet, + /// The pipelines timed now. + window: std::collections::HashSet, + /// The place the next window starts at. + next: usize, +} + +impl Sweep { + /// Notes a draw or dispatch of `pipeline`; whether the sweep times it + /// now (a pipeline not seen before joins the end of the order, and has + /// its turn after the next report at the earliest). + pub(crate) fn times(&mut self, pipeline: usize) -> bool { + let place = *self.order.entry(pipeline).or_insert_with(|| { + self.seen.push(pipeline); + self.seen.len() - 1 + }); + self.live.insert(place); + self.window.contains(&pipeline) + } + + /// After a report: the next `n` of the pipelines drawn with since the + /// one before, from where the last window ended, round the end of the + /// order. Pipelines the title no longer draws with (a menu's, a loading + /// screen's) have no turn. Returns how many it times now and how many + /// were drawn with. + pub(crate) fn advance(&mut self, n: usize) -> (usize, usize) { + let live = std::mem::take(&mut self.live); + let from = self.next; + let turn: Vec = live + .range(from..) + .chain(live.range(..from)) + .take(n) + .copied() + .collect(); + self.next = turn.last().map_or(0, |&place| place + 1); + self.window = turn.iter().map(|&place| self.seen[place]).collect(); + (turn.len(), live.len()) + } +} + +/// The key of the commands no list is cut between (those of pipelines not +/// listed or not in the sweep's window): no title pipeline has it (a null +/// pipeline draws nothing). +pub(crate) const REST: usize = 0; + +/// What tells a command's list from another's, and whether as a dispatch: +/// the title pipeline and its kind if it gets lists of its own (`own`), +/// or [`REST`]. +pub(crate) fn key(pipeline: usize, compute: bool, own: bool) -> (usize, bool) { + if own && pipeline != REST { + (pipeline, compute) + } else { + (REST, false) + } +} + +/// What a host list runs, once its first draw or dispatch is recorded. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Timed { + pub(crate) key: usize, + pub(crate) compute: bool, + /// Draws and dispatches recorded. + pub(crate) commands: u32, + /// The title pipeline's shaders, as the log names them. + pub(crate) name: String, +} + +/// Whether a command of `key` goes into a new host list: the list has +/// commands of another kind or pipeline. A list with none takes it. +pub(crate) fn cuts(current: Option<&Timed>, key: usize, compute: bool) -> bool { + current.is_some_and(|t| t.key != key || t.compute != compute) +} + +/// A timed list's line in the report: its kind and pipeline. +pub(crate) fn label(timed: Option<&Timed>) -> String { + match timed { + None => "no draw or dispatch (uploads, copies, clears)".into(), + Some(t) if t.key == REST => "the draws and dispatches not cut apart".into(), + Some(t) => format!("{} {}", if t.compute { "dispatch" } else { "draw" }, t.name), + } +} + +/// Wall time of the lists since the last report, by [`label`]. +#[derive(Default)] +pub(crate) struct Walls { + by: HashMap, + /// Every list's milliseconds, for the floor. + all: Vec, +} + +#[derive(Default)] +struct Wall { + ms: f64, + lists: u64, + commands: u64, + /// Frames it had lists in, and the last of them. + frames: u64, + last: Option, +} + +/// One pipeline's share of the frames it had lists in. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Row { + pub(crate) label: String, + /// Milliseconds a frame it had lists in. + pub(crate) ms: f64, + /// Of them, above the floor its lists would cost empty. + pub(crate) above: f64, + /// Lists and commands a frame it had lists in. + pub(crate) lists: f64, + pub(crate) commands: f64, + /// The frames it had lists in. + pub(crate) frames: u64, +} + +impl Walls { + /// A list that took `ms`, submitted in frame `frame` (frames do not go + /// back). + pub(crate) fn add(&mut self, ms: f64, timed: Option<&Timed>, frame: u64) { + let e = self.by.entry(label(timed)).or_default(); + e.ms += ms; + e.lists += 1; + e.commands += u64::from(timed.map_or(0, |t| t.commands)); + if e.last != Some(frame) { + e.last = Some(frame); + e.frames += 1; + } + self.all.push(ms as f32); + } + + /// What a list costs whatever it runs (submitting it and waiting for + /// it): the tenth percentile of the lists' milliseconds. + pub(crate) fn floor(&self) -> f64 { + if self.all.is_empty() { + return 0.0; + } + let mut all = self.all.clone(); + let at = all.len() / 10; + let (_, floor, _) = all.select_nth_unstable_by(at, f32::total_cmp); + f64::from(*floor) + } + + /// Over `frames` frames: lists and milliseconds a frame, the floor, and + /// the pipelines, each per frame it had lists in, costliest above the + /// floor first. + pub(crate) fn report(&self, frames: f64) -> (f64, f64, f64, Vec) { + let frames = frames.max(1.0); + let floor = self.floor(); + let mut rows: Vec = self + .by + .iter() + .map(|(label, w)| { + let ran = w.frames.max(1) as f64; + Row { + label: label.clone(), + ms: w.ms / ran, + above: (w.ms - floor * w.lists as f64).max(0.0) / ran, + lists: w.lists as f64 / ran, + commands: w.commands as f64 / ran, + frames: w.frames, + } + }) + .collect(); + rows.sort_by(|a, b| { + b.above + .total_cmp(&a.above) + .then_with(|| a.label.cmp(&b.label)) + }); + let total: f64 = self.by.values().map(|w| w.ms).sum(); + (self.all.len() as f64 / frames, total / frames, floor, rows) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn timed(key: usize, compute: bool, commands: u32) -> Timed { + Timed { + key, + compute, + commands, + name: format!("[{key:x}]"), + } + } + + #[test] + fn the_switch_is_off_unset_or_zero_and_names_its_modes() { + assert_eq!(mode_of(None), Mode::Off); + assert_eq!(mode_of(Some("0")), Mode::Off); + for sweep in [ + "1", + "sweep", + " Sweep ", + "", + "true", + "0123", + "0123456789abcdeg", + "sweep:0", + "sweep:x", + ] { + assert_eq!(mode_of(Some(sweep)), Mode::Sweep(SWEEP), "{sweep:?}"); + } + assert_eq!(mode_of(Some("sweep:8")), Mode::Sweep(8)); + assert_eq!(mode_of(Some("SWEEP: 40")), Mode::Sweep(40)); + let Mode::Listed(hashes) = mode_of(Some("B6DF66AF105D8B2D, 63381c3250b287fa,")) else { + panic!("two hashes are a list"); + }; + assert_eq!(hashes, ["b6df66af105d8b2d", "63381c3250b287fa"]); + assert!(lists(&hashes, "[compute 63381c3250b287fa]")); + assert!(lists( + &hashes, + "[mesh 0000000000000001, pixel b6df66af105d8b2d]" + )); + assert!(!lists(&hashes, "[compute 0000000000000002]")); + } + + /// Only the pipelines that get lists of their own leave the list the + /// rest shares, draws and dispatches alike. + #[test] + fn only_a_pipeline_with_lists_of_its_own_is_cut_from_the_rest() { + assert_eq!(key(0x1000, true, false), (REST, false)); + assert_eq!(key(0x1000, true, false), key(0x2000, false, false)); + assert_eq!(key(0x3000, true, true), (0x3000, true)); + assert_eq!(key(REST, false, true), (REST, false)); + let rest = timed(REST, false, 7); + assert!(!cuts(Some(&rest), REST, false)); + assert!(cuts(Some(&rest), 0x3000, true)); + let own = timed(0x3000, true, 1); + assert!(!cuts(Some(&own), 0x3000, true)); + assert!(cuts(Some(&own), REST, false)); + } + + /// A list takes its first command; then only its own pipeline's, and a + /// compute pipeline's dispatch is not a draw of the same pointer. + #[test] + fn a_list_is_cut_where_the_pipeline_or_the_kind_changes() { + assert!(!cuts(None, 0x1000, true)); + let list = timed(0x1000, true, 1); + assert!(!cuts(Some(&list), 0x1000, true)); + assert!(cuts(Some(&list), 0x2000, true)); + assert!(cuts(Some(&list), 0x1000, false)); + } + + /// A sweep times a window of the pipelines drawn with since the last + /// report, in the order they were first seen, moves on at each report, + /// wraps, takes in pipelines seen later and passes over those the title + /// stopped drawing with. + #[test] + fn a_sweep_goes_round_the_live_pipelines_a_window_at_a_time() { + let mut sweep = Sweep::default(); + let all: Vec = (1..=5).map(|i| i * 0x100).collect(); + let draw = |sweep: &mut Sweep, with: &[usize]| -> Vec { + with.iter().copied().filter(|&p| sweep.times(p)).collect() + }; + // Nothing is timed before the first report. + assert_eq!(draw(&mut sweep, &all), []); + assert_eq!(sweep.advance(2), (2, 5)); + assert_eq!(draw(&mut sweep, &all), [0x100, 0x200]); + assert_eq!(sweep.advance(2), (2, 5)); + assert_eq!(draw(&mut sweep, &all), [0x300, 0x400]); + // The window wraps round the end. + assert_eq!(sweep.advance(2), (2, 5)); + assert_eq!(draw(&mut sweep, &all), [0x100, 0x500]); + // The title stops drawing with 0x200 and 0x300 and starts with + // 0x600: the sweep goes on after 0x100 with what is drawn with. + let now = [0x100, 0x400, 0x500, 0x600]; + assert_eq!(sweep.advance(2), (2, 5)); + assert_eq!(draw(&mut sweep, &now), []); + assert_eq!(sweep.advance(2), (2, 4)); + assert_eq!(draw(&mut sweep, &now), [0x400, 0x500]); + assert_eq!(sweep.advance(2), (2, 4)); + assert_eq!(draw(&mut sweep, &now), [0x100, 0x600]); + // A window as wide as the scene times it all; no draws, no window. + assert_eq!(sweep.advance(16), (4, 4)); + assert_eq!(draw(&mut sweep, &now), now); + assert_eq!(sweep.advance(16), (4, 4)); + assert_eq!(sweep.advance(16), (0, 0)); + assert_eq!(draw(&mut sweep, &now), []); + } + + /// The floor is what the cheap lists cost; a pipeline's time above it + /// leaves that out for each of its lists, and ranks the report. + #[test] + fn the_report_ranks_pipelines_by_their_time_above_the_floor() { + let mut walls = Walls::default(); + // Two frames: 18 cheap lists of pipeline A (0.25 ms each), two + // heavy lists of B (10 ms each), one upload list. + for i in 0..18 { + walls.add(0.25, Some(&timed(0xa, false, 2)), i / 9); + } + for frame in 0..2 { + walls.add(10.0, Some(&timed(0xb, true, 1)), frame); + } + walls.add(0.25, None, 1); + assert_eq!(walls.floor(), 0.25); + let (lists, ms, floor, rows) = walls.report(2.0); + assert_eq!((lists, floor), (10.5, 0.25)); + assert!((ms - (18.0 * 0.25 + 20.0 + 0.25) / 2.0).abs() < 1e-9); + assert_eq!(rows[0].label, "dispatch [b]"); + assert!((rows[0].ms - 10.0).abs() < 1e-9 && (rows[0].above - 9.75).abs() < 1e-9); + assert_eq!( + (rows[0].lists, rows[0].commands, rows[0].frames), + (1.0, 1.0, 2) + ); + let a = rows + .iter() + .find(|r| r.label == "draw [a]") + .expect("pipeline A"); + assert_eq!( + (a.above, a.lists, a.commands, a.frames), + (0.0, 9.0, 18.0, 2) + ); + assert!( + rows.iter() + .any(|r| r.label.starts_with("no draw or dispatch")) + ); + } + + /// A pipeline whose turn covered three of a report's ten frames has + /// its cost per frame it had lists in, not a third of it. + #[test] + fn a_pipeline_timed_in_part_of_the_frames_is_not_diluted() { + let mut walls = Walls::default(); + for frame in 0..10 { + walls.add(1.0, Some(&timed(REST, false, 100)), frame); + if (4..7).contains(&frame) { + walls.add(20.0, Some(&timed(0xc, true, 1)), frame); + } + } + let (_, ms, _, rows) = walls.report(10.0); + assert!((ms - 7.0).abs() < 1e-9); + let c = &rows[0]; + assert_eq!( + (c.label.as_str(), c.frames, c.lists), + ("dispatch [c]", 3, 1.0) + ); + assert!((c.ms - 20.0).abs() < 1e-9); + let rest = rows + .iter() + .find(|r| r.label.starts_with("the draws")) + .expect("the rest"); + assert_eq!((rest.frames, rest.ms), (10, 1.0)); + } + + #[test] + fn the_commands_left_together_have_one_line() { + let rest = timed(REST, false, 40); + assert_eq!(label(Some(&rest)), "the draws and dispatches not cut apart"); + assert_eq!(Walls::default().report(0.0), (0.0, 0.0, 0.0, Vec::new())); + } +}