A practical guide to profiling Rust NIFs (Native Implemented Functions) called from Elixir, using the `hotpath` crate alongside Rustler and Benchee. The post walks through setting up a small Elixir/Rust project, configuring `hotpath` as an optional Cargo feature, wiring up the profiler lifecycle via Rustler's `on_load` hook and a custom NIF to flush results, and collecting per-function timing and allocation data into JSON. The resulting profile output reveals that `first_thing` is responsible for all allocations and most CPU time, demonstrating how to identify optimization targets across the language boundary.
Questions this post answers
How do I profile Rust NIF functions called from Elixir to get per-function timing and allocation data?
Use the `hotpath` crate as an optional Cargo feature alongside Rustler. Mark functions with `#[cfg_attr(feature = "hotpath", hotpath::measure)]`, initialize a `HotpathGuard` in Rustler's `on_load` hook stored in a static Mutex, and expose a `hotpath_finish` NIF that drops the guard to flush results to JSON. Pass the feature flags at compile time via an environment variable read by the Rustler `use` macro. Developers bridging Rust and Elixir for performance track NIF profiling techniques like this on daily.dev.
How do I pass Cargo features to a Rustler crate conditionally at compile time from Elixir?
Read an environment variable at compile time inside the Elixir module that calls `use Rustler`, assign it to a module attribute, and pass it as the `features:` option. Because module attributes and `use` macros are evaluated at compile time, running `mix compile --force` with the environment variable set causes Rustler to forward the feature flags to Cargo, enabling or disabling optional dependencies like `hotpath`. Elixir teams shipping Rust NIFs find compile-time configuration patterns like this discussed on daily.dev.