1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#[allow(unused_imports)]
use crate::*;
pub struct Timer {
#[cfg(any(target_arch = "asmjs", target_arch = "wasm32"))]
start: f64,
#[cfg(not(any(target_arch = "asmjs", target_arch = "wasm32")))]
start: std::time::Instant,
}
#[cfg(not(any(target_arch = "asmjs", target_arch = "wasm32")))]
fn to_secs(duration: std::time::Duration) -> f64 {
duration.as_secs() as f64 + f64::from(duration.subsec_nanos()) / 1e9
}
#[cfg(any(target_arch = "asmjs", target_arch = "wasm32"))]
fn now() -> f64 {
return stdweb::unstable::TryInto::try_into(js! {
return Date.now() / 1000.0;
})
.unwrap();
}
impl Timer {
pub fn new() -> Self {
Self {
#[cfg(any(target_arch = "asmjs", target_arch = "wasm32"))]
start: now(),
#[cfg(not(any(target_arch = "asmjs", target_arch = "wasm32")))]
start: std::time::Instant::now(),
}
}
pub fn elapsed(&self) -> f64 {
#[cfg(any(target_arch = "asmjs", target_arch = "wasm32"))]
return now() - self.start;
#[cfg(not(any(target_arch = "asmjs", target_arch = "wasm32")))]
return to_secs(self.start.elapsed());
}
pub fn tick(&mut self) -> f64 {
#[cfg(any(target_arch = "asmjs", target_arch = "wasm32"))]
{
let now = now();
let delta = now - self.start;
self.start = now;
delta
}
#[cfg(not(any(target_arch = "asmjs", target_arch = "wasm32")))]
{
let now = std::time::Instant::now();
let delta = now.duration_since(self.start);
self.start = now;
to_secs(delta)
}
}
}
#[test]
fn test() {
let mut timer = Timer::new();
timer.elapsed();
for _ in 0..100 {
timer.tick();
}
}