]> git.lizzy.rs Git - rust.git/blob - crates/profile/src/lib.rs
5ea5039dbadc0d1214b1c8d450d2f58f0c15d2d9
[rust.git] / crates / profile / src / lib.rs
1 //! A collection of tools for profiling rust-analyzer.
2
3 mod stop_watch;
4 mod memory_usage;
5 #[cfg(feature = "cpu_profiler")]
6 mod google_cpu_profiler;
7 mod hprof;
8 mod tree;
9
10 use std::cell::RefCell;
11
12 pub use crate::{
13     hprof::{heartbeat, heartbeat_span, init, init_from, span},
14     memory_usage::{Bytes, MemoryUsage},
15     stop_watch::{StopWatch, StopWatchSpan},
16 };
17
18 pub use countme;
19 /// Include `_c: Count<Self>` field in important structs to count them.
20 ///
21 /// To view the counts, run with `RA_COUNT=1`. The overhead of disabled count is
22 /// almost zero.
23 pub use countme::Count;
24
25 thread_local!(static IN_SCOPE: RefCell<bool> = RefCell::new(false));
26
27 /// Allows to check if the current code is withing some dynamic scope, can be
28 /// useful during debugging to figure out why a function is called.
29 pub struct Scope {
30     prev: bool,
31 }
32
33 impl Scope {
34     #[must_use]
35     pub fn enter() -> Scope {
36         let prev = IN_SCOPE.with(|slot| std::mem::replace(&mut *slot.borrow_mut(), true));
37         Scope { prev }
38     }
39     pub fn is_active() -> bool {
40         IN_SCOPE.with(|slot| *slot.borrow())
41     }
42 }
43
44 impl Drop for Scope {
45     fn drop(&mut self) {
46         IN_SCOPE.with(|slot| *slot.borrow_mut() = self.prev);
47     }
48 }
49
50 /// A wrapper around google_cpu_profiler.
51 ///
52 /// Usage:
53 /// 1. Install gpref_tools (<https://github.com/gperftools/gperftools>), probably packaged with your Linux distro.
54 /// 2. Build with `cpu_profiler` feature.
55 /// 3. Run the code, the *raw* output would be in the `./out.profile` file.
56 /// 4. Install pprof for visualization (<https://github.com/google/pprof>).
57 /// 5. Bump sampling frequency to once per ms: `export CPUPROFILE_FREQUENCY=1000`
58 /// 6. Use something like `pprof -svg target/release/rust-analyzer ./out.profile` to see the results.
59 ///
60 /// For example, here's how I run profiling on NixOS:
61 ///
62 /// ```bash
63 /// $ bat -p shell.nix
64 /// with import <nixpkgs> {};
65 /// mkShell {
66 ///   buildInputs = [ gperftools ];
67 ///   shellHook = ''
68 ///     export LD_LIBRARY_PATH="${gperftools}/lib:"
69 ///   '';
70 /// }
71 /// $ set -x CPUPROFILE_FREQUENCY 1000
72 /// $ nix-shell --run 'cargo test --release --package rust-analyzer --lib -- benchmarks::benchmark_integrated_highlighting --exact --nocapture'
73 /// $ pprof -svg target/release/deps/rust_analyzer-8739592dc93d63cb crates/rust-analyzer/out.profile > profile.svg
74 /// ```
75 ///
76 /// See this diff for how to profile completions:
77 ///
78 /// <https://github.com/rust-analyzer/rust-analyzer/pull/5306>
79 #[derive(Debug)]
80 pub struct CpuSpan {
81     _private: (),
82 }
83
84 #[must_use]
85 pub fn cpu_span() -> CpuSpan {
86     #[cfg(feature = "cpu_profiler")]
87     {
88         google_cpu_profiler::start("./out.profile".as_ref())
89     }
90
91     #[cfg(not(feature = "cpu_profiler"))]
92     {
93         eprintln!(
94             r#"cpu profiling is disabled, uncomment `default = [ "cpu_profiler" ]` in Cargo.toml to enable."#
95         )
96     }
97
98     CpuSpan { _private: () }
99 }
100
101 impl Drop for CpuSpan {
102     fn drop(&mut self) {
103         #[cfg(feature = "cpu_profiler")]
104         {
105             google_cpu_profiler::stop();
106             let profile_data = std::env::current_dir().unwrap().join("out.profile");
107             eprintln!("Profile data saved to:\n\n    {}\n", profile_data.display());
108             let mut cmd = std::process::Command::new("pprof");
109             cmd.arg("-svg").arg(std::env::current_exe().unwrap()).arg(&profile_data);
110             let out = cmd.output();
111
112             match out {
113                 Ok(out) if out.status.success() => {
114                     let svg = profile_data.with_extension("svg");
115                     std::fs::write(&svg, &out.stdout).unwrap();
116                     eprintln!("Profile rendered to:\n\n    {}\n", svg.display());
117                 }
118                 _ => {
119                     eprintln!("Failed to run:\n\n   {:?}\n", cmd);
120                 }
121             }
122         }
123     }
124 }
125
126 pub fn memory_usage() -> MemoryUsage {
127     MemoryUsage::now()
128 }