embedded_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 PerformanceCounter {
11    pub fn new() -> Self {
12        Self {
13            start_of_frame: std::time::Instant::now(),
14            old_point: std::time::Instant::now(),
15            text: String::new(),
16            old_text: String::new(),
17            only_fps: false,
18        }
19    }
20
21    pub fn only_fps(&mut self, only_fps: bool) {
22        self.only_fps = only_fps;
23    }
24
25    pub fn start_of_frame(&mut self) {
26        self.start_of_frame = std::time::Instant::now();
27        self.old_point = self.start_of_frame;
28        self.text.clear();
29    }
30
31    pub fn add_measurement(&mut self, label: &str) {
32        if self.only_fps {
33            return;
34        }
35        let now = std::time::Instant::now();
36        let ms = (now - self.old_point).as_micros();
37        self.text += &format!("{}: {}\n", label, ms);
38        self.old_point = now;
39    }
40
41    pub fn discard_measurement(&mut self) {
42        if self.only_fps {
43            return;
44        }
45        self.old_point = std::time::Instant::now();
46    }
47
48    pub fn print(&mut self) {
49        if !self.only_fps {
50            self.text += &format!(
51                "total: {}\n",
52                (std::time::Instant::now() - self.start_of_frame).as_micros()
53            );
54        }
55        self.text += &format!(
56            "fps: {}",
57            1_000_000 / (std::time::Instant::now() - self.start_of_frame).as_micros()
58        );
59
60        self.old_text = self.text.clone();
61    }
62
63    pub fn get_text(&self) -> &str {
64        &self.old_text
65    }
66}