voxel_framework/profile.rs
1//! Internal profiling helpers.
2//!
3//! All instrumentation in this crate goes through the `profile_span!` macro
4//! exported from the crate root. With the `tracing` Cargo feature **off** the
5//! macro expands to nothing, so there is zero overhead in default builds.
6//!
7//! # Cargo features
8//!
9//! | Feature | Effect |
10//! |---------|--------|
11//! | (none) | All `profile_span!` invocations compile to nothing. |
12//! | `tracing` | Hot paths emit `tracing` spans. Consumers attach their own subscriber. |
13//! | `tracy` | Implies `tracing`, plus a helper `init_tracy` that sets up a `tracing-tracy` subscriber for live profiling with a Tracy client. |
14//!
15//! # Usage
16//!
17//! ```rust,ignore
18//! use voxel_framework::profile_span;
19//!
20//! pub fn hot_path() {
21//! profile_span!("voxel::mesh::greedy");
22//! // ... work that should appear in the profile ...
23//! }
24//! ```
25//!
26//! For Tracy:
27//!
28//! ```rust,ignore
29//! fn main() {
30//! #[cfg(feature = "tracy")]
31//! voxel_framework::profile::init_tracy();
32//!
33//! bevy::prelude::App::new()/* ... */.run();
34//! }
35//! ```
36//!
37//! [`tracing`]: https://docs.rs/tracing
38//! [`tracing-tracy`]: https://docs.rs/tracing-tracy
39
40#[cfg(feature = "tracing")]
41pub use tracing::{Level, instrument, span};
42
43/// Opens a profiling span scoped to the enclosing block.
44///
45/// Compiles to nothing when the `tracing` feature is disabled.
46///
47/// # Example
48///
49/// ```rust,ignore
50/// use voxel_framework::profile_span;
51///
52/// fn generate() {
53/// profile_span!("voxel::mesh::greedy");
54/// // expensive work
55/// }
56/// ```
57#[macro_export]
58macro_rules! profile_span {
59 ($name:expr) => {
60 #[cfg(feature = "tracing")]
61 let _voxel_profile_span = ::tracing::span!(::tracing::Level::INFO, $name).entered();
62 };
63}
64
65/// Installs a `tracing` subscriber that forwards spans to a Tracy client.
66///
67/// Call this **once** from your binary's `main()` **before** constructing the
68/// Bevy [`App`](bevy::app::App). The function is intentionally not auto-invoked
69/// because most games already register their own subscriber and only one global
70/// subscriber may be active at a time.
71///
72/// # Panics
73///
74/// Panics if a global default subscriber has already been installed.
75#[cfg(feature = "tracy")]
76pub fn init_tracy() {
77 use tracing_subscriber::layer::SubscriberExt;
78 use tracing_subscriber::util::SubscriberInitExt;
79
80 tracing_subscriber::registry()
81 .with(tracing_tracy::TracyLayer::default())
82 .init();
83}