From 8ff0c6481a3cab6fce2ae6f2ef8ccbed76a4fa6a Mon Sep 17 00:00:00 2001 From: NonbinaryCoder <108490895+NonbinaryCoder@users.noreply.github.com> Date: Thu, 22 May 2025 15:04:24 -0400 Subject: [PATCH] Diagnostic reset sum ema (#19337) # Objective Fix incorrect average returned by `Diagnostic` after `clear_history` is called. ## Solution Reset sum and ema values in `Diagnostic::clear_history`. ## Testing I have added a cargo test for `Diagnostic::clear_history` that checks average and smoothed average. This test passes, and should not be platform dependent. --- crates/bevy_diagnostic/src/diagnostic.rs | 30 ++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/crates/bevy_diagnostic/src/diagnostic.rs b/crates/bevy_diagnostic/src/diagnostic.rs index 00a758416b..675f205a64 100644 --- a/crates/bevy_diagnostic/src/diagnostic.rs +++ b/crates/bevy_diagnostic/src/diagnostic.rs @@ -293,6 +293,8 @@ impl Diagnostic { /// Clear the history of this diagnostic. pub fn clear_history(&mut self) { self.history.clear(); + self.sum = 0.0; + self.ema = 0.0; } } @@ -420,3 +422,31 @@ impl RegisterDiagnostic for App { self } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_clear_history() { + const MEASUREMENT: f64 = 20.0; + + let mut diagnostic = + Diagnostic::new(DiagnosticPath::new("test")).with_max_history_length(5); + let mut now = Instant::now(); + + for _ in 0..3 { + for _ in 0..5 { + diagnostic.add_measurement(DiagnosticMeasurement { + time: now, + value: MEASUREMENT, + }); + // Increase time to test smoothed average. + now += Duration::from_secs(1); + } + assert!((diagnostic.average().unwrap() - MEASUREMENT).abs() < 0.1); + assert!((diagnostic.smoothed().unwrap() - MEASUREMENT).abs() < 0.1); + diagnostic.clear_history(); + } + } +}