Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions d3d12/crates/leonida-gpu/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5337,6 +5337,8 @@ pub(crate) mod indirects;
mod font;
#[cfg(feature = "diagnostics")]
mod panel;
// Frame-time percentiles and what stalls frames, with the frame-rate line.
mod frametime;
// Leonida: the F1 settings menu and the frame-rate line, in every build.
mod menu;
// Leonida: the trainer menu laid over the picture (`leonida-menu`, F4).
Expand Down Expand Up @@ -12361,6 +12363,8 @@ struct Meter {
logged: std::time::Instant,
/// The caption the window had, once read.
caption: Option<Vec<u16>>,
/// Frame times and stalls, logged with the line.
stalls: frametime::Meter,
}

impl Meter {
Expand All @@ -12374,6 +12378,10 @@ impl Meter {
drawn: crate::draw::drawn(),
logged: now,
caption: None,
stalls: frametime::Meter::new(
crate::pipeline::made(),
RESIDENT[1].load(Ordering::Relaxed),
),
}
}

Expand All @@ -12389,6 +12397,7 @@ impl Meter {
tracing::debug!(target: "leonida_gpu::frame", token = crate::frame::current(), "present");
#[cfg(feature = "diagnostics")]
crate::copystat::presented();
self.stalls.presented(std::time::Instant::now());
self.frames += 1;
#[cfg(feature = "diagnostics")]
{
Expand All @@ -12409,6 +12418,13 @@ impl Meter {
let five = self.logged.elapsed() >= std::time::Duration::from_secs(5);
if five {
self.logged = std::time::Instant::now();
// (Here: the frame times are this meter's.)
self.stalls.line(
crate::pipeline::making(),
crate::pipeline::made(),
RESIDENT[1].load(Ordering::Relaxed),
crate::residency::available_commit(),
);
}
// (The copy counters run from one five-second line to the next.)
#[cfg(feature = "diagnostics")]
Expand Down
284 changes: 284 additions & 0 deletions d3d12/crates/leonida-gpu/src/host/frametime.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,284 @@
//! Frame times as a distribution, not only a mean, so that stalls show: every
//! presented frame's time goes in, and with the frame-rate line, every five
//! seconds, one line gives the median, the 95th and 99th percentiles, the
//! longest frame and how many took over 100 ms and over a second, beside what
//! stalls frames: host pipelines queued and made a second, waits for new
//! memory to be resident, and the commit the system has left. The panel (F3)
//! shows the last one.

use std::time::Instant;

/// Frame times kept for the percentiles of one line (about 13 s at 300 fps);
/// past it the counts and the longest frame stay exact.
const KEPT: usize = 4096;

/// The times of the frames since the last [`FrameTimes::take`], in ms.
#[derive(Default)]
pub(super) struct FrameTimes {
ms: Vec<f32>,
frames: u32,
longest: f32,
over_100: u32,
over_1s: u32,
}

/// What [`FrameTimes::take`] gives back, in ms. The percentiles are nearest
/// rank: a value some frame took, such that that share of frames took as
/// long or less.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(super) struct Summary {
pub(super) frames: u32,
pub(super) p50: f32,
pub(super) p95: f32,
pub(super) p99: f32,
pub(super) longest: f32,
pub(super) over_100: u32,
pub(super) over_1s: u32,
}

impl FrameTimes {
pub(super) fn push(&mut self, ms: f32) {
self.frames += 1;
self.longest = self.longest.max(ms);
self.over_100 += u32::from(ms > 100.0);
self.over_1s += u32::from(ms > 1000.0);
if self.ms.len() < KEPT {
self.ms.push(ms);
}
}

/// The frames since the last call (none: `None`), and a fresh start.
pub(super) fn take(&mut self) -> Option<Summary> {
if self.frames == 0 {
return None;
}
self.ms.sort_unstable_by(f32::total_cmp);
let n = self.ms.len();
// Nearest rank, in whole numbers: the ceil(p * n / 100)-th time.
let at = |percent: usize| self.ms[(percent * n).div_ceil(100).clamp(1, n) - 1];
let summary = Summary {
frames: self.frames,
p50: at(50),
p95: at(95),
p99: at(99),
longest: self.longest,
over_100: self.over_100,
over_1s: self.over_1s,
};
self.ms.clear();
(self.frames, self.longest, self.over_100, self.over_1s) = (0, 0.0, 0, 0);
Some(summary)
}
}

/// One line's numbers.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(super) struct Stalls {
pub(super) times: Summary,
/// Host pipelines queued or being made.
pub(super) queued: u64,
pub(super) made_per_s: f64,
/// Waits for new memory to be resident, ms a frame.
pub(super) resident_ms: f64,
pub(super) commit_left_gb: f64,
}

/// The last line's numbers, for the panel.
#[cfg(feature = "diagnostics")]
pub(super) static LAST: std::sync::Mutex<Option<Stalls>> = std::sync::Mutex::new(None);

/// The frame-rate meter's part: frame times, and the totals the next line
/// counts from.
pub(super) struct Meter {
times: FrameTimes,
last: Option<Instant>,
since: Instant,
made: u64,
resident_us: u64,
}

impl Meter {
/// From the totals so far (`made` host pipelines, `resident_us` waited for
/// new memory), so that the first line counts only what came after.
pub(super) fn new(made: u64, resident_us: u64) -> Meter {
Meter {
times: FrameTimes::default(),
last: None,
since: Instant::now(),
made,
resident_us,
}
}

/// A frame was presented at `now`.
pub(super) fn presented(&mut self, now: Instant) {
if let Some(last) = self.last.replace(now) {
self.times.push((now - last).as_secs_f32() * 1000.0);
}
}

/// Logs the line, from the totals since the start: `made` host pipelines,
/// `resident_us` waited for new memory; `queued` and `commit` (bytes) now.
pub(super) fn line(&mut self, queued: u64, made: u64, resident_us: u64, commit: u64) {
let Some(times) = self.times.take() else {
return;
};
let now = Instant::now();
let seconds = (now - self.since).as_secs_f64().max(1e-3);
let stalls = Stalls {
times,
queued,
made_per_s: made.saturating_sub(self.made) as f64 / seconds,
resident_ms: resident_us.saturating_sub(self.resident_us) as f64
/ 1e3
/ f64::from(times.frames),
commit_left_gb: commit as f64 / f64::from(1u32 << 30),
};
(self.since, self.made, self.resident_us) = (now, made, resident_us);
tracing::info!(
"frame times over {seconds:.1} s, {} frames: median {:.1} ms, 95th percentile {:.1}, 99th {:.1}, longest {:.1}; \
{} over 100 ms, {} over 1 s; host pipelines {queued} queued or being made, {:.1} made a second; waits for new memory to be \
resident {:.2} ms a frame; commit left {:.1} GB",
times.frames,
times.p50,
times.p95,
times.p99,
times.longest,
times.over_100,
times.over_1s,
stalls.made_per_s,
stalls.resident_ms,
stalls.commit_left_gb
);
#[cfg(feature = "diagnostics")]
if let Ok(mut last) = LAST.lock() {
*last = Some(stalls);
}
}
}

/// A frame time for the panel in at most four or five characters: ms up to
/// 9999, then whole seconds with an S.
#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
fn short(ms: f32) -> String {
if ms < 9999.5 {
format!("{ms:.0}")
} else {
format!("{:.0}S", ms / 1000.0)
}
}

/// The panel's lines for `s`, with `pipeline_wait_ms` a frame (summed over
/// threads, over the panel's half second; the rest over the five-second
/// line), each at most 40 characters of the panel's font.
#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
pub(super) fn panel_lines(s: &Stalls, pipeline_wait_ms: f64) -> [String; 5] {
let t = &s.times;
let (p50, p95, p99, max) = (short(t.p50), short(t.p95), short(t.p99), short(t.longest));
[
format!("P50 {p50} P95 {p95} P99 {p99} MAX {max}"),
format!("OVER 100 MS {} OVER 1 S {}", t.over_100, t.over_1s),
format!("PIPES PENDING {} MADE/S {:.1}", s.queued, s.made_per_s),
format!(
"WAITS PIPES {pipeline_wait_ms:.1} RESIDENT {:.1} MS",
s.resident_ms
),
format!("COMMIT LEFT {:.1} GB", s.commit_left_gb),
]
}

#[cfg(test)]
mod tests {
use super::{FrameTimes, Stalls, Summary, panel_lines};

#[test]
fn frame_times_give_percentiles_counts_and_the_longest() {
let mut t = FrameTimes::default();
assert_eq!(t.take(), None, "no frame, no line");
// 98 smooth frames, one hitch and one stall.
for _ in 0..98 {
t.push(10.0);
}
t.push(150.0);
t.push(2000.0);
let s = t.take().unwrap();
assert_eq!(
(s.frames, s.p50, s.p95, s.longest),
(100, 10.0, 10.0, 2000.0)
);
assert_eq!(s.p99, 150.0, "the 99th of 100 frames is the second longest");
assert_eq!((s.over_100, s.over_1s), (2, 1));
assert_eq!(t.take(), None, "taking starts afresh");
}

#[test]
fn percentiles_are_nearest_rank_without_float_rounding() {
let mut t = FrameTimes::default();
for ms in 1..=20 {
t.push(ms as f32);
}
let s = t.take().unwrap();
// ceil(0.95 * 20) = 19, ceil(0.99 * 20) = 20, ceil(0.5 * 20) = 10.
assert_eq!((s.p50, s.p95, s.p99), (10.0, 19.0, 20.0));
// Ranks are whole numbers, (percent * n).div_ceil(100), so no float
// can move one. For 50, 95 and 99 a float rank, ceil(p / 100 * n),
// happens to agree for every n up to 4096: this case pins the
// direction (up, not down) at 100 frames.
for ms in 1..=100 {
t.push(ms as f32);
}
let s = t.take().unwrap();
assert_eq!((s.p50, s.p95, s.p99), (50.0, 95.0, 99.0));
}

#[test]
fn past_the_kept_times_the_counts_stay_exact() {
let mut t = FrameTimes::default();
for _ in 0..super::KEPT {
t.push(16.0);
}
for _ in 0..10 {
t.push(1500.0);
}
let s = t.take().unwrap();
assert_eq!(s.frames as usize, super::KEPT + 10);
assert_eq!((s.over_100, s.over_1s, s.longest), (10, 10, 1500.0));
}

#[test]
fn the_panel_lines_fit_its_box_and_font() {
// Long stalls too: 10 s and more (the launcher's pipeline budget),
// up to a minute without a present.
for ms in [9999.0, 10_000.0, 99_999.0, 600_000.0] {
let s = Stalls {
times: Summary {
frames: 9999,
p50: ms,
p95: ms,
p99: ms,
longest: ms,
over_100: 9999,
over_1s: 9999,
},
queued: 99999,
made_per_s: 999.9,
resident_ms: 999.9,
commit_left_gb: 99.9,
};
for line in panel_lines(&s, 9999.9) {
assert!(
line.len() <= 40,
"{line:?} is longer than the panel's 40 columns"
);
assert!(
line.bytes().all(|c| c == b' '
|| crate::host::font::glyph(c) != crate::host::font::glyph(b'#')),
"{line:?} has a character the panel cannot draw"
);
}
}
assert_eq!(super::short(9999.0), "9999");
assert_eq!(super::short(10_000.0), "10S");
assert_eq!(super::short(600_000.0), "600S");
}
}
15 changes: 11 additions & 4 deletions d3d12/crates/leonida-gpu/src/host/panel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const GLYPH: (u32, u32) = (5, 7);
const CELL: (u32, u32) = (6, 9);
/// Characters in a line, lines, and the box's rim in dots.
const COLUMNS: u32 = 40;
const LINES: u32 = 9;
const LINES: u32 = 14;
const RIM: u32 = 3;

/// The texts are put into one of these in turn: the card reads the others,
Expand Down Expand Up @@ -118,7 +118,7 @@ fn painted(lines: &[String], scale: u32, colours: [&[u8]; 2], pitch: usize) -> V
#[derive(Clone, Copy, Default)]
struct Counters([u64; COUNTERS]);

const COUNTERS: usize = 11;
const COUNTERS: usize = 12;

impl Counters {
fn now() -> Counters {
Expand All @@ -138,6 +138,7 @@ impl Counters {
crate::drops::totals().1,
peek(C::RecordNs),
crate::draw::drawn(),
peek(C::PipelineWaitUs),
])
}

Expand All @@ -159,7 +160,9 @@ fn text(c: &[f64; COUNTERS], ms: f64, worst: f64, cost: f64, host: &Host) -> Vec
let (working, private) = crate::copystat::process_memory();
let [budget, used, _, shared] = host.video_memory().unwrap_or_default();
let idle = (c[1] / 1e3).min(ms);
vec![
// The frame-time line's last numbers (every five seconds), once there is one.
let stalls = super::frametime::LAST.lock().ok().and_then(|last| *last);
let mut lines = vec![
// LOCAL (11/26): with frame generation, the frames shown beside those rendered.
match crate::fg::shown_per_frame() {
1 => format!("FPS {:.1} FRAME {ms:.1} MS", 1e3 / ms.max(0.001)),
Expand All @@ -173,7 +176,11 @@ fn text(c: &[f64; COUNTERS], ms: f64, worst: f64, cost: f64, host: &Host) -> Vec
format!("RAM {:.1} GB IN MEMORY {:.1}", gb(private), gb(working)),
format!("VRAM {:.1}/{:.1} GB SHARED {:.1}", gb(used), gb(budget), gb(shared)),
format!("THIS PANEL {:.0} US A FRAME", cost),
]
];
if let Some(s) = stalls {
lines.extend(super::frametime::panel_lines(&s, c[11] / 1e3));
}
lines
}

/// The buffers of a box that size and format.
Expand Down
7 changes: 7 additions & 0 deletions d3d12/crates/leonida-gpu/src/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -839,6 +839,13 @@ pub(crate) fn making() -> u64 {
make::waiting()
}

/// Host pipelines created or loaded from the library since the start.
#[cfg(windows)]
pub(crate) fn made() -> u64 {
use std::sync::atomic::Ordering::Relaxed;
library::MADE.load(Relaxed) + library::LOADED.load(Relaxed)
}

/// Draws and dispatches dropped since the last [`take_drops`], by reason
/// (diagnostics).
#[cfg(all(windows, feature = "diagnostics"))]
Expand Down