box2d_rust/timer.rs
1//! Port of the timing helpers from box2d-cpp-reference/src/timer.c
2//! (`b2GetTicks`, `b2GetMilliseconds`, `b2GetMillisecondsAndReset`).
3//!
4//! Mutex / semaphore / thread wrappers from that file are not ported — Rust's
5//! standard library covers them. Only the profiling clock remains.
6//!
7//! Uses `std::time::Instant` for relative durations. On wasm32 Instant is backed
8//! by `performance.now()` in current rustc, which is enough for demo profiling
9//! (Capacity's 20 ms threshold) as well as native.
10//!
11//! SPDX-FileCopyrightText: 2023 Erin Catto
12//! SPDX-License-Identifier: MIT
13
14use std::time::Instant;
15
16/// Opaque tick capture. (return value of `b2GetTicks`)
17#[derive(Clone, Copy)]
18pub struct Ticks {
19 start: Instant,
20}
21
22/// Capture the current time. (`b2GetTicks`)
23#[inline]
24pub fn get_ticks() -> Ticks {
25 Ticks {
26 start: Instant::now(),
27 }
28}
29
30/// Milliseconds elapsed since `ticks`. (`b2GetMilliseconds`)
31#[inline]
32pub fn get_milliseconds(ticks: Ticks) -> f32 {
33 // Match C: cast the double ms value down to float.
34 (ticks.start.elapsed().as_secs_f64() * 1000.0) as f32
35}
36
37/// Milliseconds elapsed since `ticks`, then reset `ticks` to now.
38/// (`b2GetMillisecondsAndReset`)
39#[inline]
40pub fn get_milliseconds_and_reset(ticks: &mut Ticks) -> f32 {
41 let now = Instant::now();
42 let ms = (now.duration_since(ticks.start).as_secs_f64() * 1000.0) as f32;
43 ticks.start = now;
44 ms
45}
46
47#[cfg(test)]
48mod tests {
49 use super::*;
50
51 #[test]
52 fn milliseconds_are_non_negative() {
53 let ticks = get_ticks();
54 let ms = get_milliseconds(ticks);
55 assert!(ms >= 0.0);
56 }
57
58 #[test]
59 fn reset_advances_the_mark() {
60 let mut ticks = get_ticks();
61 let start = Instant::now();
62 while start.elapsed().as_nanos() < 50_000 {
63 core::hint::spin_loop();
64 }
65 let first = get_milliseconds_and_reset(&mut ticks);
66 assert!(first >= 0.0);
67 let second = get_milliseconds(ticks);
68 assert!(second >= 0.0);
69 assert!(second <= first + 1.0);
70 }
71}