profile/
lib.rs

1//! A collection of tools for profiling rust-analyzer.
2
3#[cfg(feature = "cpu_profiler")]
4mod google_cpu_profiler;
5mod memory_usage;
6mod stop_watch;
7
8use std::cell::RefCell;
9
10pub use crate::{
11    memory_usage::{Bytes, MemoryUsage},
12    stop_watch::{StopWatch, StopWatchSpan},
13};
14
15thread_local!(static IN_SCOPE: RefCell<bool> = const { RefCell::new(false) });
16
17/// A wrapper around google_cpu_profiler.
18///
19/// Usage:
20/// 1. Install gperf_tools (<https://github.com/gperftools/gperftools>), probably packaged with your Linux distro.
21/// 2. Build with `cpu_profiler` feature.
22/// 3. Run the code, the *raw* output would be in the `./out.profile` file.
23/// 4. Install pprof for visualization (<https://github.com/google/pprof>).
24/// 5. Bump sampling frequency to once per ms: `export CPUPROFILE_FREQUENCY=1000`
25/// 6. Use something like `pprof -svg target/release/rust-analyzer ./out.profile` to see the results.
26///
27/// For example, here's how I run profiling on NixOS:
28///
29/// ```bash
30/// $ bat -p shell.nix
31/// with import <nixpkgs> {};
32/// mkShell {
33///   buildInputs = [ gperftools ];
34///   shellHook = ''
35///     export LD_LIBRARY_PATH="${gperftools}/lib:"
36///   '';
37/// }
38/// $ set -x CPUPROFILE_FREQUENCY 1000
39/// $ nix-shell --run 'cargo test --release --package rust-analyzer --lib -- benchmarks::benchmark_integrated_highlighting --exact --nocapture'
40/// $ pprof -svg target/release/deps/rust_analyzer-8739592dc93d63cb crates/rust-analyzer/out.profile > profile.svg
41/// ```
42///
43/// See this diff for how to profile completions:
44///
45/// <https://github.com/rust-lang/rust-analyzer/pull/5306>
46#[derive(Debug)]
47pub struct CpuSpan {
48    _private: (),
49}
50
51#[must_use]
52pub fn cpu_span() -> CpuSpan {
53    #[cfg(feature = "cpu_profiler")]
54    {
55        google_cpu_profiler::start("./out.profile".as_ref())
56    }
57
58    #[cfg(not(feature = "cpu_profiler"))]
59    #[allow(clippy::print_stderr)]
60    {
61        eprintln!(
62            r#"cpu profiling is disabled, uncomment `default = [ "cpu_profiler" ]` in Cargo.toml to enable."#
63        );
64    }
65
66    CpuSpan { _private: () }
67}
68
69impl Drop for CpuSpan {
70    fn drop(&mut self) {
71        #[cfg(feature = "cpu_profiler")]
72        {
73            google_cpu_profiler::stop();
74            let profile_data = std::env::current_dir().unwrap().join("out.profile");
75            eprintln!("Profile data saved to:\n\n    {}\n", profile_data.display());
76            let mut cmd = std::process::Command::new("pprof");
77            cmd.arg("-svg").arg(std::env::current_exe().unwrap()).arg(&profile_data);
78            let out = cmd.output();
79
80            match out {
81                Ok(out) if out.status.success() => {
82                    let svg = profile_data.with_extension("svg");
83                    std::fs::write(&svg, out.stdout).unwrap();
84                    eprintln!("Profile rendered to:\n\n    {}\n", svg.display());
85                }
86                _ => {
87                    eprintln!("Failed to run:\n\n   {cmd:?}\n");
88                }
89            }
90        }
91    }
92}
93
94pub fn memory_usage() -> MemoryUsage {
95    MemoryUsage::now()
96}