rapier3d/counters/
timer.rs1use std::{
2 fmt::{Display, Error, Formatter},
3 time::Duration,
4};
5
6#[cfg(feature = "profiler")]
7use web_time::Instant;
8
9#[derive(Copy, Clone, Debug, Default)]
11pub struct Timer {
12 time: Duration,
13 #[cfg(feature = "profiler")]
14 start: Option<Instant>,
15}
16
17impl Timer {
18 pub fn new() -> Self {
20 Timer {
21 time: Duration::from_secs(0),
22 #[cfg(feature = "profiler")]
23 start: None,
24 }
25 }
26
27 pub fn reset(&mut self) {
29 self.time = Duration::from_secs(0)
30 }
31
32 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 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 pub fn resume(&mut self) {
54 #[cfg(feature = "profiler")]
55 {
56 self.start = Some(Instant::now());
57 }
58 }
59
60 pub fn time(&self) -> Duration {
62 self.time
63 }
64
65 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}