Skip to main content

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 an `Instant` for relative durations. On native targets this is
8//! `std::time::Instant`. On `wasm32-unknown-unknown`, `std::time::Instant::now()`
9//! panics ("time not implemented on this platform"), so we use the `web-time`
10//! crate there instead — its `Instant` is backed by `performance.now()`. That
11//! provides real wall-clock values needed for demo profiling (Capacity's 20 ms
12//! threshold) without trapping every world step.
13//!
14//! SPDX-FileCopyrightText: 2023 Erin Catto
15//! SPDX-License-Identifier: MIT
16
17#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
18use std::time::Instant;
19#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
20use web_time::Instant;
21
22/// Opaque tick capture. (return value of `b2GetTicks`)
23#[derive(Clone, Copy)]
24pub struct Ticks {
25    start: Instant,
26}
27
28/// Capture the current time. (`b2GetTicks`)
29#[inline]
30pub fn get_ticks() -> Ticks {
31    Ticks {
32        start: Instant::now(),
33    }
34}
35
36/// Milliseconds elapsed since `ticks`. (`b2GetMilliseconds`)
37#[inline]
38pub fn get_milliseconds(ticks: Ticks) -> f32 {
39    // Match C: cast the double ms value down to float.
40    (ticks.start.elapsed().as_secs_f64() * 1000.0) as f32
41}
42
43/// Milliseconds elapsed since `ticks`, then reset `ticks` to now.
44/// (`b2GetMillisecondsAndReset`)
45#[inline]
46pub fn get_milliseconds_and_reset(ticks: &mut Ticks) -> f32 {
47    let now = Instant::now();
48    let ms = (now.duration_since(ticks.start).as_secs_f64() * 1000.0) as f32;
49    ticks.start = now;
50    ms
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn milliseconds_are_non_negative() {
59        let ticks = get_ticks();
60        let ms = get_milliseconds(ticks);
61        assert!(ms >= 0.0);
62    }
63
64    #[test]
65    fn reset_advances_the_mark() {
66        let mut ticks = get_ticks();
67        let start = Instant::now();
68        while start.elapsed().as_nanos() < 50_000 {
69            core::hint::spin_loop();
70        }
71        let first = get_milliseconds_and_reset(&mut ticks);
72        assert!(first >= 0.0);
73        let second = get_milliseconds(ticks);
74        assert!(second >= 0.0);
75        assert!(second <= first + 1.0);
76    }
77}