risc0_core/perf.rs
1// Copyright 2024 RISC Zero, Inc.
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 at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Utilities for gathering performance data.
16
17use core::fmt::Display;
18
19pub use puffin;
20
21#[doc(hidden)]
22pub struct NvtxRange;
23
24impl NvtxRange {
25 #[doc(hidden)]
26 #[inline]
27 #[must_use]
28 pub fn new<M: Display>(msg: M) -> Self {
29 nvtx::__private::_range_push(msg);
30 Self
31 }
32}
33
34impl Drop for NvtxRange {
35 #[inline]
36 fn drop(&mut self) {
37 nvtx::__private::_range_pop();
38 }
39}
40
41/// Opens a scope.
42#[macro_export]
43macro_rules! scope {
44 ($name:expr) => {
45 // Keep range alive until caller's block scope ends.
46 let _nvtx = $crate::perf::NvtxRange::new($name);
47 $crate::perf::puffin::profile_scope!($name);
48 };
49
50 ($name:expr, $body:expr) => {{
51 // Keep range alive while `$body` is evaluated.
52 let _nvtx = $crate::perf::NvtxRange::new($name);
53 $crate::perf::puffin::profile_scope!($name);
54 $body
55 }};
56}
57
58/// Opens a scope with a formatted message.
59#[macro_export]
60macro_rules! scope_with {
61 ($name:expr, $data:expr) => {
62 // Keep range alive until caller's block scope ends.
63 let _nvtx = $crate::perf::NvtxRange::new(::core::format_args!($name, $data));
64 $crate::perf::puffin::profile_scope!($name, $data);
65 };
66
67 ($name:expr, $data:expr, $body:expr) => {{
68 // Keep range alive while `$body` is evaluated.
69 let _nvtx = $crate::perf::NvtxRange::new(::core::format_args!($name, $data));
70 $crate::perf::puffin::profile_scope!($name, $data);
71 $body
72 }};
73}