//! Measures the frames presented by the game in wall-clock time. use std::time::{Duration, Instant}; #[derive(Default)] pub(super) struct FrameRate { sample: Option<(Instant, u64)>, displayed: Option, } impl FrameRate { pub(super) fn presented(&mut self, now: Instant, frames: u64) -> Option { let (start, first_frame) = *self.sample.get_or_insert((now, frames)); let elapsed = now.saturating_duration_since(start); if elapsed < Duration::from_secs(1) { return None; } self.sample = Some((now, frames)); let fps = ((frames - first_frame) as f64 / elapsed.as_secs_f64()).round() as u32; (self.displayed.replace(fps) != Some(fps)).then_some(fps) } } #[cfg(test)] #[test] fn reports_presentations_per_elapsed_second() { let mut rate = FrameRate::default(); let start = Instant::now(); assert_eq!(rate.presented(start, 1), None); assert_eq!(rate.presented(start + Duration::from_millis(950), 57), None); assert_eq!( rate.presented(start + Duration::from_millis(1200), 73), Some(60) ); assert_eq!( rate.presented(start + Duration::from_millis(2200), 133), None ); assert_eq!( rate.presented(start + Duration::from_millis(3200), 163), Some(30) ); }