profile_traits/
time.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use base::cross_process_instant::CrossProcessInstant;
6use ipc_channel::ipc::IpcSender;
7use log::warn;
8use malloc_size_of_derive::MallocSizeOf;
9use serde::{Deserialize, Serialize};
10use time::Duration;
11
12#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
13pub struct TimerMetadata {
14    pub url: String,
15    pub iframe: TimerMetadataFrameType,
16    pub incremental: TimerMetadataReflowType,
17}
18
19#[derive(Clone, Debug, Deserialize, Serialize)]
20pub struct ProfilerChan(pub IpcSender<ProfilerMsg>);
21
22impl ProfilerChan {
23    pub fn send(&self, msg: ProfilerMsg) {
24        if let Err(e) = self.0.send(msg) {
25            warn!("Error communicating with the time profiler thread: {}", e);
26        }
27    }
28}
29
30#[derive(Clone, Debug, Deserialize, Serialize)]
31pub enum ProfilerData {
32    NoRecords,
33    Record(Vec<Duration>),
34}
35
36#[derive(Clone, Debug, Deserialize, Serialize)]
37pub enum ProfilerMsg {
38    /// Normal message used for reporting time
39    Time(
40        (ProfilerCategory, Option<TimerMetadata>),
41        (CrossProcessInstant, CrossProcessInstant),
42    ),
43    /// Message used to get time spend entries for a particular ProfilerBuckets (in nanoseconds)
44    Get(
45        (ProfilerCategory, Option<TimerMetadata>),
46        IpcSender<ProfilerData>,
47    ),
48    /// Message used to force print the profiling metrics
49    Print,
50
51    /// Report a layout query that could not be processed immediately for a particular URL.
52    BlockedLayoutQuery(String),
53
54    /// Tells the profiler to shut down.
55    Exit(IpcSender<()>),
56}
57
58/// Usage sites of variants marked “Rust tracing only” are not visible to rust-analyzer.
59#[repr(u32)]
60#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
61pub enum ProfilerCategory {
62    /// The compositor is rasterising or presenting.
63    ///
64    /// Not associated with a specific URL.
65    Compositing = 0x00,
66
67    /// The script thread is doing layout work.
68    Layout = 0x10,
69
70    ImageSaving = 0x51,
71    ScriptAttachLayout = 0x60,
72    ScriptConstellationMsg = 0x61,
73    ScriptDevtoolsMsg = 0x62,
74    ScriptDocumentEvent = 0x63,
75
76    /// Rust tracing only: the script thread is executing a script.
77    /// This may include time doing layout or parse work initiated by the script.
78    ScriptEvaluate = 0x65,
79
80    ScriptEvent = 0x66,
81    ScriptFileRead = 0x67,
82    ScriptFontLoading = 0x68,
83    ScriptImageCacheMsg = 0x69,
84    ScriptInputEvent = 0x6a,
85    ScriptNetworkEvent = 0x6b,
86
87    /// The script thread is parsing HTML, rather than doing other work like evaluating scripts or doing layout.
88    ScriptParseHTML = 0x6c,
89
90    ScriptPlannedNavigation = 0x6d,
91    ScriptResize = 0x6e,
92    ScriptRendering = 0x6f,
93    ScriptSetScrollState = 0x70,
94    ScriptSetViewport = 0x71,
95    ScriptTimerEvent = 0x72,
96    ScriptStylesheetLoad = 0x73,
97    ScriptUpdateReplacedElement = 0x74,
98    ScriptWebSocketEvent = 0x75,
99    ScriptWorkerEvent = 0x76,
100    ScriptServiceWorkerEvent = 0x77,
101
102    /// The script thread is parsing XML, rather than doing other work like evaluating scripts or doing layout.
103    ScriptParseXML = 0x78,
104
105    ScriptEnterFullscreen = 0x79,
106    ScriptExitFullscreen = 0x7a,
107    ScriptWorkletEvent = 0x7b,
108    ScriptPerformanceEvent = 0x7c,
109    ScriptHistoryEvent = 0x7d,
110    ScriptPortMessage = 0x7e,
111    ScriptWebGPUMsg = 0x7f,
112
113    ScriptDatabaseAccessEvent = 0x80,
114
115    /// Web performance metrics.
116    TimeToFirstPaint = 0x90,
117    TimeToFirstContentfulPaint = 0x91,
118    TimeToInteractive = 0x92,
119
120    IpcReceiver = 0x93,
121    IpcBytesReceiver = 0x94,
122}
123
124impl ProfilerCategory {
125    pub const fn variant_name(&self) -> &'static str {
126        match self {
127            ProfilerCategory::Compositing => "Compositing",
128            ProfilerCategory::Layout => "Layout",
129            ProfilerCategory::ImageSaving => "ImageSaving",
130            ProfilerCategory::ScriptAttachLayout => "ScriptAttachLayout",
131            ProfilerCategory::ScriptConstellationMsg => "ScriptConstellationMsg",
132            ProfilerCategory::ScriptDatabaseAccessEvent => "ScriptDatabaseAccessEvent",
133            ProfilerCategory::ScriptDevtoolsMsg => "ScriptDevtoolsMsg",
134            ProfilerCategory::ScriptDocumentEvent => "ScriptDocumentEvent",
135            ProfilerCategory::ScriptEvaluate => "ScriptEvaluate",
136            ProfilerCategory::ScriptEvent => "ScriptEvent",
137            ProfilerCategory::ScriptFileRead => "ScriptFileRead",
138            ProfilerCategory::ScriptFontLoading => "ScriptFontLoading",
139            ProfilerCategory::ScriptImageCacheMsg => "ScriptImageCacheMsg",
140            ProfilerCategory::ScriptInputEvent => "ScriptInputEvent",
141            ProfilerCategory::ScriptNetworkEvent => "ScriptNetworkEvent",
142            ProfilerCategory::ScriptParseHTML => "ScriptParseHTML",
143            ProfilerCategory::ScriptPlannedNavigation => "ScriptPlannedNavigation",
144            ProfilerCategory::ScriptRendering => "ScriptRendering",
145            ProfilerCategory::ScriptResize => "ScriptResize",
146            ProfilerCategory::ScriptSetScrollState => "ScriptSetScrollState",
147            ProfilerCategory::ScriptSetViewport => "ScriptSetViewport",
148            ProfilerCategory::ScriptTimerEvent => "ScriptTimerEvent",
149            ProfilerCategory::ScriptStylesheetLoad => "ScriptStylesheetLoad",
150            ProfilerCategory::ScriptUpdateReplacedElement => "ScriptUpdateReplacedElement",
151            ProfilerCategory::ScriptWebSocketEvent => "ScriptWebSocketEvent",
152            ProfilerCategory::ScriptWorkerEvent => "ScriptWorkerEvent",
153            ProfilerCategory::ScriptServiceWorkerEvent => "ScriptServiceWorkerEvent",
154            ProfilerCategory::ScriptParseXML => "ScriptParseXML",
155            ProfilerCategory::ScriptEnterFullscreen => "ScriptEnterFullscreen",
156            ProfilerCategory::ScriptExitFullscreen => "ScriptExitFullscreen",
157            ProfilerCategory::ScriptWorkletEvent => "ScriptWorkletEvent",
158            ProfilerCategory::ScriptPerformanceEvent => "ScriptPerformanceEvent",
159            ProfilerCategory::ScriptHistoryEvent => "ScriptHistoryEvent",
160            ProfilerCategory::ScriptPortMessage => "ScriptPortMessage",
161            ProfilerCategory::ScriptWebGPUMsg => "ScriptWebGPUMsg",
162            ProfilerCategory::TimeToFirstPaint => "TimeToFirstPaint",
163            ProfilerCategory::TimeToFirstContentfulPaint => "TimeToFirstContentfulPaint",
164            ProfilerCategory::TimeToInteractive => "TimeToInteractive",
165            ProfilerCategory::IpcReceiver => "IpcReceiver",
166            ProfilerCategory::IpcBytesReceiver => "IpcBytesReceiver",
167        }
168    }
169}
170
171#[derive(Clone, Debug, Deserialize, Eq, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)]
172pub enum TimerMetadataFrameType {
173    RootWindow,
174    IFrame,
175}
176
177#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
178pub enum TimerMetadataReflowType {
179    Incremental,
180    FirstReflow,
181}
182
183#[cfg(feature = "tracing")]
184pub type Span = tracing::Span;
185#[cfg(not(feature = "tracing"))]
186pub type Span = ();
187
188pub fn profile<T, F>(
189    category: ProfilerCategory,
190    meta: Option<TimerMetadata>,
191    profiler_chan: ProfilerChan,
192    #[cfg(feature = "tracing")] span: Span,
193    #[cfg(not(feature = "tracing"))] _span: Span,
194    callback: F,
195) -> T
196where
197    F: FnOnce() -> T,
198{
199    let start_time = CrossProcessInstant::now();
200    let val = {
201        #[cfg(feature = "tracing")]
202        let _enter = span.enter();
203        callback()
204    };
205    let end_time = CrossProcessInstant::now();
206
207    send_profile_data(category, meta, &profiler_chan, start_time, end_time);
208    val
209}
210
211pub fn send_profile_data(
212    category: ProfilerCategory,
213    meta: Option<TimerMetadata>,
214    profiler_chan: &ProfilerChan,
215    start_time: CrossProcessInstant,
216    end_time: CrossProcessInstant,
217) {
218    profiler_chan.send(ProfilerMsg::Time((category, meta), (start_time, end_time)));
219}