1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
//! 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<u32>,
}
impl FrameRate {
pub(super) fn presented(&mut self, now: Instant, frames: u64) -> Option<u32> {
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)
);
}
|