orinium_browser/profile.rs
1//! Compile-time-gated profiling instrumentation.
2//!
3//! Timers are declared with [`macro@perf_scope`] and results are reported
4//! through [`macro@profile_log`]. Both expand to nothing unless the `profile`
5//! feature is enabled.
6
7/// Declares a named timer for the enclosing scope.
8///
9/// ```ignore
10/// fn foo() {
11/// perf_scope!(total);
12///
13/// do_something();
14///
15/// profile_log!(
16/// target: "perf",
17/// log::Level::Info,
18/// "foo: {:?}",
19/// total.elapsed(),
20/// );
21/// }
22/// ```
23///
24/// Expands to nothing when the `profile` feature is disabled, so every use of
25/// the declared binding must live inside a [`macro@profile_log!`] invocation
26/// (or its own `#[cfg(any(feature = "profile", debug_assertions))]` gate).
27#[macro_export]
28macro_rules! perf_scope {
29 ($name:ident) => {
30 #[cfg(any(feature = "profile", debug_assertions))]
31 let $name = std::time::Instant::now();
32 };
33}
34
35/// Logs profiling information; compiled out unless the `profile` feature is
36/// enabled.
37///
38/// Arguments are neither evaluated nor formatted when disabled.
39#[macro_export]
40macro_rules! profile_log {
41 (target: $target:expr, $level:expr, $($arg:tt)+) => {{
42 #[cfg(any(feature = "profile", debug_assertions))]
43 log::log!(target: $target, $level, $($arg)+);
44 }};
45}
46
47/// Shortens `text` to a bounded preview for profile log output.
48#[cfg(any(feature = "profile", debug_assertions))]
49pub(crate) fn text_preview(text: &str) -> String {
50 const MAX_LEN: usize = 40;
51
52 if text.len() <= MAX_LEN {
53 return text.to_string();
54 }
55 let mut end = MAX_LEN;
56 while !text.is_char_boundary(end) {
57 end -= 1;
58 }
59 format!("{}...", &text[..end])
60}