/
profiler.rs
77 lines (64 loc) · 1.87 KB
/
profiler.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#[cfg(feature = "pprof")]
mod implementation {
extern crate pprof;
pub(crate) struct Profiler {
enabled: bool,
guard: Option<pprof::ProfilerGuard<'static>>,
}
impl Profiler {
pub(crate) fn new(enabled: bool) -> Self {
Self {
enabled,
guard: None,
}
}
pub(crate) fn start(&mut self) {
if self.enabled {
self.guard = Some(pprof::ProfilerGuard::new(100).unwrap())
} else {
self.guard = None
}
}
pub(crate) fn stop(&mut self) -> Result<(), Box<dyn std::error::Error>> {
if self.enabled {
println!("Creating flamegraph.svg");
let report = self.guard.take().unwrap().report().build()?;
let file = std::fs::File::create("flamegraph.svg").unwrap();
report.flamegraph(file)?;
}
Ok(())
}
}
impl Default for Profiler {
fn default() -> Self {
Self::new(false)
}
}
impl std::fmt::Debug for Profiler {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Profiler")
.field("enabled", &self.enabled)
.finish()
}
}
impl std::str::FromStr for Profiler {
type Err = String;
fn from_str(_: &str) -> Result<Self, Self::Err> {
Ok(Self::new(true))
}
}
}
#[cfg(not(feature = "pprof"))]
mod implementation {
pub(crate) struct Profiler {}
impl Profiler {
pub(crate) fn new(_: bool) -> Self {
Self {}
}
pub(crate) fn start(&mut self) {}
pub(crate) fn stop(&mut self) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
}
}
pub(crate) use implementation::Profiler;