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