1#[cfg(not(target_arch = "wasm32"))]
18use std::time::Instant;
19
20use crate::error::{BacktraceError, ErrorMessage};
21#[cfg(target_arch = "wasm32")]
22use crate::web::{WebPerformance, WebWindow};
23
24pub struct Stopwatch
26{
27 clock: TimeClock,
28 start: TimeInstant
29}
30
31impl Stopwatch
32{
33 #[inline]
35 pub fn new() -> Result<Self, BacktraceError<ErrorMessage>>
36 {
37 let clock = TimeClock::new()?;
38 let start = clock.now();
39
40 Ok(Self { clock, start })
41 }
42
43 #[inline]
45 pub fn secs_elapsed(&self) -> f64
46 {
47 self.clock.secs_elapsed_since(&self.start)
48 }
49}
50
51#[derive(Clone)]
53struct TimeClock
54{
55 #[cfg(target_arch = "wasm32")]
56 performance: WebPerformance
57}
58
59impl TimeClock
60{
61 pub fn new() -> Result<Self, BacktraceError<ErrorMessage>>
63 {
64 #[cfg(target_arch = "wasm32")]
65 return Ok(Self {
66 performance: WebWindow::new()?.performance()?
67 });
68
69 #[cfg(not(target_arch = "wasm32"))]
70 return Ok(Self {});
71 }
72
73 #[inline]
75 pub fn now(&self) -> TimeInstant
76 {
77 #[cfg(target_arch = "wasm32")]
78 return TimeInstant {
79 value: self.performance.now()
80 };
81
82 #[cfg(not(target_arch = "wasm32"))]
83 return TimeInstant {
84 value: Instant::now()
85 };
86 }
87
88 #[inline]
91 pub fn secs_elapsed_since(&self, start: &TimeInstant) -> f64
92 {
93 #[cfg(target_arch = "wasm32")]
94 return (self.now().value - start.value) / 1000.0;
95
96 #[cfg(not(target_arch = "wasm32"))]
97 return start.value.elapsed().as_secs_f64();
98 }
99}
100
101struct TimeInstant
103{
104 #[cfg(target_arch = "wasm32")]
105 value: f64,
106
107 #[cfg(not(target_arch = "wasm32"))]
108 value: Instant
109}