use core::fmt;
use core::time::Duration;
use crate::debug::{DEFAULT_FRAME_WINDOW, DebugModule, DebugSection};
pub use crcbl_core::stats::MIN_PERCENTILE_SAMPLES;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Bound {
Unknown,
Cpu,
Gpu,
Tied,
}
impl Bound {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Unknown => "unknown",
Self::Cpu => "cpu",
Self::Gpu => "gpu",
Self::Tied => "tied",
}
}
}
impl fmt::Display for Bound {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
type Window = crcbl_core::stats::Window<DEFAULT_FRAME_WINDOW>;
#[derive(Clone, Debug, Default)]
pub struct BudgetStats {
cpu: Window,
gpu: Window,
gpu_frame: Option<u64>,
}
impl BudgetStats {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn record_cpu(&mut self, cpu: Duration) {
self.cpu.record(nanos_of(cpu));
}
pub fn record_gpu(&mut self, frame: u64, gpu: Duration) -> bool {
if self.gpu_frame == Some(frame) {
return false;
}
self.gpu_frame = Some(frame);
self.gpu.record(nanos_of(gpu));
true
}
#[must_use]
pub fn has_samples(&self) -> bool {
!self.cpu.is_empty() || !self.gpu.is_empty()
}
#[must_use]
pub fn cpu(&self) -> Option<(Duration, Duration)> {
self.cpu.percentiles().map(durations_of)
}
#[must_use]
pub fn gpu(&self) -> Option<(Duration, Duration)> {
self.gpu.percentiles().map(durations_of)
}
#[must_use]
pub const fn gpu_frame(&self) -> Option<u64> {
self.gpu_frame
}
#[must_use]
pub fn bound(&self) -> Bound {
let (Some((cpu, _)), Some((gpu, _))) = (self.cpu.percentiles(), self.gpu.percentiles())
else {
return Bound::Unknown;
};
match gpu.cmp(&cpu) {
core::cmp::Ordering::Greater => Bound::Gpu,
core::cmp::Ordering::Less => Bound::Cpu,
core::cmp::Ordering::Equal => Bound::Tied,
}
}
}
fn write_window(out: &mut DebugSection, label: &str, window: &Window) {
match window.percentiles() {
Some((p50, p95)) => out.row(
label,
format_args!("{:.2} / {:.2} ms", millis(p50), millis(p95)),
),
None if window.is_empty() => out.row_str(label, "none"),
None => out.row(
label,
format_args!("filling {}/{}", window.len(), MIN_PERCENTILE_SAMPLES),
),
}
}
fn millis(nanos: u64) -> f64 {
nanos as f64 / 1.0e6
}
fn nanos_of(duration: Duration) -> u64 {
u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX)
}
fn durations_of((p50, p95): (u64, u64)) -> (Duration, Duration) {
(Duration::from_nanos(p50), Duration::from_nanos(p95))
}
impl DebugModule for BudgetStats {
fn debug_section(&self, out: &mut DebugSection) {
out.set_title("budget");
write_window(out, "cpu p50/p95", &self.cpu);
write_window(out, "gpu elapsed p50/p95", &self.gpu);
out.row_str("bound", self.bound().as_str());
match self.gpu_frame {
Some(frame) => out.row("gpu frame", format_args!("{frame}")),
None => out.row_str("gpu frame", "pending"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ms(millis: u64) -> Duration {
Duration::from_millis(millis)
}
fn fill(stats: &mut BudgetStats, n: usize, cpu: u64, gpu: u64) {
for frame in 0..n {
stats.record_cpu(ms(cpu));
stats.record_gpu(frame as u64, ms(gpu));
}
}
#[test]
fn a_short_window_reports_how_full_it_is_rather_than_a_percentile() {
let mut stats = BudgetStats::new();
assert!(!stats.has_samples());
assert_eq!(stats.cpu(), None);
assert_eq!(stats.bound(), Bound::Unknown);
assert_eq!(rendered(&stats, "cpu p50/p95"), "none");
assert_eq!(rendered(&stats, "gpu frame"), "pending");
fill(&mut stats, MIN_PERCENTILE_SAMPLES - 1, 4, 8);
assert!(stats.has_samples());
assert_eq!(stats.cpu(), None, "one sample short is still short");
assert_eq!(stats.bound(), Bound::Unknown);
assert_eq!(rendered(&stats, "cpu p50/p95"), "filling 19/20");
assert_eq!(rendered(&stats, "bound"), "unknown");
fill(&mut stats, 1, 4, 8);
assert_eq!(stats.cpu(), Some((ms(4), ms(4))));
assert_eq!(stats.bound(), Bound::Gpu);
}
#[test]
fn the_budget_is_whichever_side_has_the_larger_p50() {
let mut gpu_bound = BudgetStats::new();
fill(&mut gpu_bound, MIN_PERCENTILE_SAMPLES, 4, 9);
assert_eq!(gpu_bound.cpu(), Some((ms(4), ms(4))));
assert_eq!(gpu_bound.gpu(), Some((ms(9), ms(9))));
assert_eq!(gpu_bound.bound(), Bound::Gpu);
assert_eq!(gpu_bound.bound().to_string(), "gpu");
let mut cpu_bound = BudgetStats::new();
fill(&mut cpu_bound, MIN_PERCENTILE_SAMPLES, 9, 4);
assert_eq!(cpu_bound.bound(), Bound::Cpu);
let mut tied = BudgetStats::new();
fill(&mut tied, MIN_PERCENTILE_SAMPLES, 5, 5);
assert_eq!(tied.bound(), Bound::Tied);
let mut half = BudgetStats::new();
for _ in 0..MIN_PERCENTILE_SAMPLES {
half.record_cpu(ms(4));
}
assert!(half.cpu().is_some());
assert_eq!(half.gpu(), None);
assert_eq!(half.bound(), Bound::Unknown);
}
#[test]
fn re_reading_the_same_gpu_frame_does_not_fill_the_window() {
let mut stats = BudgetStats::new();
assert!(stats.record_gpu(7, ms(3)), "a frame not seen before");
assert!(!stats.record_gpu(7, ms(3)), "the same frame again");
assert!(!stats.record_gpu(7, ms(99)), "even at a different cost");
assert_eq!(stats.gpu.len(), 1);
assert_eq!(stats.gpu_frame(), Some(7));
assert!(stats.record_gpu(8, ms(3)));
assert_eq!(stats.gpu.len(), 2);
assert_eq!(stats.gpu_frame(), Some(8));
}
#[test]
fn the_window_holds_the_frame_rows_worth_of_frames_and_then_evicts() {
let mut stats = BudgetStats::new();
stats.record_cpu(ms(500));
for _ in 0..DEFAULT_FRAME_WINDOW {
stats.record_cpu(ms(4));
}
assert_eq!(stats.cpu.len(), DEFAULT_FRAME_WINDOW);
assert_eq!(
stats.cpu(),
Some((ms(4), ms(4))),
"the 500 ms frame has scrolled out of the window"
);
}
#[test]
fn the_row_renders_the_numbers_it_was_given() {
let mut stats = BudgetStats::new();
fill(&mut stats, MIN_PERCENTILE_SAMPLES, 4, 9);
let mut section = DebugSection::default();
stats.debug_section(&mut section);
assert_eq!(section.title(), "budget");
assert_eq!(rendered(&stats, "cpu p50/p95"), "4.00 / 4.00 ms");
assert_eq!(rendered(&stats, "gpu elapsed p50/p95"), "9.00 / 9.00 ms");
assert_eq!(rendered(&stats, "bound"), "gpu");
assert_eq!(
rendered(&stats, "gpu frame"),
(MIN_PERCENTILE_SAMPLES - 1).to_string(),
);
let mut other = BudgetStats::new();
for frame in 0..MIN_PERCENTILE_SAMPLES {
other.record_cpu(ms(20));
other.record_gpu(frame as u64, ms(1));
}
assert_eq!(rendered(&other, "cpu p50/p95"), "20.00 / 20.00 ms");
assert_eq!(rendered(&other, "gpu elapsed p50/p95"), "1.00 / 1.00 ms");
assert_eq!(rendered(&other, "bound"), "cpu");
}
#[test]
fn the_two_percentiles_are_read_off_the_same_window_separately() {
let mut stats = BudgetStats::new();
for value in 1..=MIN_PERCENTILE_SAMPLES as u64 {
stats.record_cpu(ms(value));
}
assert_eq!(stats.cpu(), Some((ms(10), ms(19))));
assert_eq!(rendered(&stats, "cpu p50/p95"), "10.00 / 19.00 ms");
}
#[test]
fn the_sections_labels_are_its_own() {
let mut section = DebugSection::default();
BudgetStats::new().debug_section(&mut section);
let labels: Vec<&str> = section
.rows()
.iter()
.map(|row| row.label.as_str())
.collect();
assert_eq!(
labels,
["cpu p50/p95", "gpu elapsed p50/p95", "bound", "gpu frame"],
);
}
fn rendered(stats: &BudgetStats, label: &str) -> String {
let mut section = DebugSection::default();
stats.debug_section(&mut section);
section
.rows()
.iter()
.find(|row| row.label == label)
.unwrap_or_else(|| panic!("no {label:?} row in {:?}", section.rows()))
.value
.clone()
}
}