rapier3d/counters/
timer.rs

1use std::{
2    fmt::{Display, Error, Formatter},
3    time::Duration,
4};
5
6#[cfg(feature = "profiler")]
7use web_time::Instant;
8
9/// A timer.
10#[derive(Copy, Clone, Debug, Default)]
11pub struct Timer {
12    time: Duration,
13    #[cfg(feature = "profiler")]
14    start: Option<Instant>,
15}
16
17impl Timer {
18    /// Creates a new timer initialized to zero and not started.
19    pub fn new() -> Self {
20        Timer {
21            time: Duration::from_secs(0),
22            #[cfg(feature = "profiler")]
23            start: None,
24        }
25    }
26
27    /// Resets the timer to 0.
28    pub fn reset(&mut self) {
29        self.time = Duration::from_secs(0)
30    }
31
32    /// Start the timer.
33    pub fn start(&mut self) {
34        #[cfg(feature = "profiler")]
35        {
36            self.time = Duration::from_secs(0);
37            self.start = Some(Instant::now());
38        }
39    }
40
41    /// Pause the timer.
42    pub fn pause(&mut self) {
43        #[cfg(feature = "profiler")]
44        {
45            if let Some(start) = self.start {
46                self.time += Instant::now().duration_since(start);
47            }
48            self.start = None;
49        }
50    }
51
52    /// Resume the timer.
53    pub fn resume(&mut self) {
54        #[cfg(feature = "profiler")]
55        {
56            self.start = Some(Instant::now());
57        }
58    }
59
60    /// The measured time between the last `.start()` and `.pause()` calls.
61    pub fn time(&self) -> Duration {
62        self.time
63    }
64
65    /// The measured time in milliseconds between the last `.start()` and `.pause()` calls.
66    pub fn time_ms(&self) -> f64 {
67        self.time.as_secs_f64() * 1000.0
68    }
69}
70
71impl Display for Timer {
72    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
73        write!(f, "{}ms", self.time_ms())
74    }
75}