Skip to main content

hopr_platform/
time.rs

1pub mod native {
2    pub fn current_time() -> std::time::SystemTime {
3        std::time::SystemTime::now()
4    }
5}
6
7pub use native::current_time;
8
9/// Wraps an expression with optional TRACE-level timing instrumentation.
10///
11/// When the `trace-timing` feature is enabled, the macro measures the elapsed
12/// time of the body expression and emits a `tracing::trace!` log with an
13/// `elapsed_ms` field. The timing overhead is further gated behind
14/// `tracing::enabled!(tracing::Level::TRACE)` so that `Instant::now()` is
15/// only called when a TRACE subscriber is active.
16///
17/// When the feature is disabled, the macro evaluates to just the body.
18///
19/// # Variants
20///
21/// ```ignore
22/// // Simple: label + body
23/// let val = trace_timed!("my_operation", { some_async_fn().await? });
24///
25/// // With extra tracing fields
26/// let val = trace_timed!("my_operation", packet_type = "fwd", { body });
27/// ```
28#[cfg(feature = "trace-timing")]
29#[macro_export]
30macro_rules! trace_timed {
31    ($label:expr, { $($body:tt)* }) => {{
32        let __trace_timing = tracing::enabled!(tracing::Level::TRACE);
33        let __trace_start = __trace_timing.then(std::time::Instant::now);
34        let __trace_result = { $($body)* };
35        if let Some(__start) = __trace_start {
36            tracing::trace!(elapsed_ms = __start.elapsed().as_millis() as u64, $label);
37        }
38        __trace_result
39    }};
40    ($label:expr, $($field:ident = $val:expr),+, { $($body:tt)* }) => {{
41        let __trace_timing = tracing::enabled!(tracing::Level::TRACE);
42        let __trace_start = __trace_timing.then(std::time::Instant::now);
43        let __trace_result = { $($body)* };
44        if let Some(__start) = __trace_start {
45            tracing::trace!(elapsed_ms = __start.elapsed().as_millis() as u64, $($field = $val),+, $label);
46        }
47        __trace_result
48    }};
49}
50
51#[cfg(not(feature = "trace-timing"))]
52#[macro_export]
53macro_rules! trace_timed {
54    ($label:expr, { $($body:tt)* }) => {{ $($body)* }};
55    ($label:expr, $($field:ident = $val:expr),+, { $($body:tt)* }) => {{ $($body)* }};
56}