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 > 1_000_000 {
33        bail!("Sub-microsecond intervals are not supported.");
34    }
35    let sample_freq = c_int::try_from(sample_freq)?;
36    let pg = ProfilerGuard::new(sample_freq)?;
37    time::sleep(total_time).await;
38    let builder = pg.report();
39    let report = builder.build_unresolved()?;
40    let mut profile = StackProfile::default();
41    for (f, weight) in report.data {
42        let thread_name;
43        // No other known way to convert `*mut c_void` to `usize`.
44        #[allow(clippy::as_conversions)]
45        let mut addrs: Vec<_> = f.frames.iter().map(|f| f.ip() as usize).collect();
46        addrs.reverse();
47        // No other known way to convert `isize` to `f64`.
48        #[allow(clippy::as_conversions)]
49        let weight = weight as f64;
50        let anno = if merge_threads {
51            None
52        } else {
53            thread_name = String::from_utf8_lossy(&f.thread_name[0..f.thread_name_length]);
54            Some(thread_name.as_ref())
55        };
56        let stack = WeightedStack { addrs, weight };
57        profile.push_stack(stack, anno);
58    }
59
60    Ok(profile)
61}