clay_utils/
counter.rs

1use std::{
2    time::Duration,
3    f64::NAN,
4};
5
6
7pub struct FrameCounter {
8    fps: f64,
9    tacc: Duration,
10    /// Exponential decay factor of previous values.
11    /// Deafult value is `0.1`.
12    pub decay: f64,
13    /// logging period
14    /// Deafult is 2 seconds.
15    pub log_period: Option<Duration>,
16}
17
18impl FrameCounter {
19    pub fn new() -> Self {
20        Self {
21            fps: NAN, tacc: Duration::from_secs(0),
22            decay: 1e-1, log_period: None,
23        }
24    }
25
26    pub fn new_with_log(log_period: Duration) -> Self {
27        Self {
28            fps: NAN, tacc: Duration::from_secs(0),
29            decay: 1e-1, log_period: Some(log_period),
30        }
31    }
32
33    /// Frames per second.
34    pub fn fps(&self) -> f64 {
35        self.fps
36    }
37
38    pub fn step_frame(&mut self, time: Duration, n_passes: usize) {
39        let cfps = (n_passes as f64)/((time.as_secs() as f64) + 1e-6*(time.as_micros() as f64));
40        if self.fps.is_nan() {
41            self.fps = cfps;
42        } else {
43            self.fps = (1.0 - self.decay)*self.fps + self.decay*cfps;
44        }
45
46        self.tacc += time;
47        if let Some(log_period) = self.log_period {
48            if self.tacc > log_period {
49                println!("FPS: {:.2}", self.fps);
50                self.tacc = Duration::from_secs(0);
51            }
52        }
53    }
54}
55
56