mz_prof/time.rs
1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License in the LICENSE file at the
6// root of this repository, or online at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use std::os::raw::c_int;
17
18use anyhow::bail;
19use pprof::ProfilerGuard;
20use pprof_util::{StackProfile, WeightedStack};
21use tokio::time::{self, Duration};
22
23/// # Safety
24///
25/// Nothing else must be attempting to unwind backtraces while this is called.
26/// In particular, jemalloc memory profiling must be off.
27pub async unsafe fn prof_time(
28 total_time: Duration,
29 sample_freq: u32,
30 merge_threads: bool,
31) -> anyhow::Result<StackProfile> {
32 if sample_freq == 0 {
33 bail!("Sampling frequency must be greater than zero.");
34 }
35 if sample_freq > 1_000_000 {
36 bail!("Sub-microsecond intervals are not supported.");
37 }
38 let sample_freq = c_int::try_from(sample_freq)?;
39 let pg = ProfilerGuard::new(sample_freq)?;
40 time::sleep(total_time).await;
41 let builder = pg.report();
42 let report = builder.build_unresolved()?;
43 let mut profile = StackProfile::default();
44 for (f, weight) in report.data {
45 let thread_name;
46 // No other known way to convert `*mut c_void` to `usize`.
47 #[allow(clippy::as_conversions)]
48 let mut addrs: Vec<_> = f
49 .frames
50 .iter()
51 .map(|f| f.ip() as usize)
52 // Drop null instruction pointers. The sampler can emit `ip() == 0`
53 // for empty/unresolvable frames; downstream pprof conversion computes
54 // `addr - 1`, which underflows on 0 (panics in debug builds with
55 // overflow checks enabled, wraps to a bogus address in release).
56 .filter(|ip| *ip != 0)
57 .collect();
58 addrs.reverse();
59 // No other known way to convert `isize` to `f64`.
60 #[allow(clippy::as_conversions)]
61 let weight = weight as f64;
62 let anno = if merge_threads {
63 None
64 } else {
65 thread_name = String::from_utf8_lossy(&f.thread_name[0..f.thread_name_length]);
66 Some(thread_name.as_ref())
67 };
68 let stack = WeightedStack { addrs, weight };
69 profile.push_stack(stack, anno);
70 }
71
72 Ok(profile)
73}