Skip to main content

drm_gfx/
perfcounter.rs

1#[derive(Debug)]
2pub struct PerformanceCounter {
3    start_of_frame: std::time::Instant,
4    old_point: std::time::Instant,
5    text: String,
6    old_text: String,
7    only_fps: bool,
8}
9
10impl Default for PerformanceCounter {
11    fn default() -> Self {
12        Self::new()
13    }
14}
15
16impl PerformanceCounter {
17    pub fn new() -> Self {
18        Self {
19            start_of_frame: std::time::Instant::now(),
20            old_point: std::time::Instant::now(),
21            text: String::new(),
22            old_text: String::new(),
23            only_fps: false,
24        }
25    }
26
27    pub fn only_fps(&mut self, only_fps: bool) {
28        self.only_fps = only_fps;
29    }
30
31    pub fn get_frametime(&self) -> u64 {
32        (std::time::Instant::now() - self.start_of_frame).as_micros() as u64
33    }
34
35    pub fn start_of_frame(&mut self) {
36        self.start_of_frame = std::time::Instant::now();
37        self.old_point = self.start_of_frame;
38        self.text.clear();
39    }
40
41    pub fn add_measurement(&mut self, label: &str) {
42        if self.only_fps {
43            return;
44        }
45        let now = std::time::Instant::now();
46        let ms = (now - self.old_point).as_micros();
47        self.text += &format!("{label}: {ms}\n");
48        self.old_point = now;
49    }
50
51    pub fn discard_measurement(&mut self) {
52        if self.only_fps {
53            return;
54        }
55        self.old_point = std::time::Instant::now();
56    }
57
58    pub fn print(&mut self) {
59        if !self.only_fps {
60            self.text += &format!(
61                "total: {}\n",
62                (std::time::Instant::now() - self.start_of_frame).as_micros()
63            );
64        }
65        self.text += &format!(
66            "fps: {}",
67            1_000_000 / (std::time::Instant::now() - self.start_of_frame).as_micros()
68        );
69
70        self.old_text = self.text.clone();
71    }
72
73    pub fn get_text(&self) -> &str {
74        &self.old_text
75    }
76}