Skip to main content

gpui/
profiler.rs

1//! Profiling utilities for task, frame, and thread performance tracking.
2
3#[cfg(feature = "profiler")]
4use hdrhistogram::Histogram;
5use itertools::Itertools;
6use scheduler::{Instant, SpawnTime};
7#[cfg(feature = "profiler")]
8use smallvec::SmallVec;
9use std::{
10    cell::LazyCell,
11    collections::{HashMap, VecDeque},
12    hash::{DefaultHasher, Hash, Hasher},
13    sync::{
14        Arc,
15        atomic::{AtomicU64, Ordering},
16    },
17    thread::ThreadId,
18    time::Duration,
19};
20
21mod actions;
22#[cfg(feature = "profiler")]
23pub mod hang;
24#[cfg(feature = "profiler")]
25pub mod journal;
26pub use actions::{ActionStatistics, ActionTiming, take_action_stats};
27
28use serde::{Deserialize, Serialize};
29
30#[cfg(feature = "profiler")]
31use crate::{Action, App, WindowId};
32use crate::{SharedString, TasksIncluded};
33
34#[cfg(feature = "profiler")]
35#[doc(hidden)]
36pub fn get_all_timings(included: gpui::TasksIncluded) -> Vec<gpui::ThreadTaskTimings> {
37    ThreadTaskTimings::collect(upgraded_thread_timings(), included)
38}
39
40#[cfg(feature = "profiler")]
41#[doc(hidden)]
42pub fn get_current_thread_timings(included: TasksIncluded) -> gpui::ThreadTaskTimings {
43    gpui::profiler::get_current_thread_task_timings(included)
44}
45
46#[cfg(feature = "profiler")]
47#[doc(hidden)]
48pub fn take_all_stats(included: TasksIncluded) -> Vec<gpui::ThreadTaskStatistics> {
49    ThreadTaskStatistics::collect_and_reset(upgraded_thread_timings(), included)
50}
51
52#[cfg(not(feature = "profiler"))]
53#[doc(hidden)]
54pub fn get_all_timings(_included: gpui::TasksIncluded) -> Vec<gpui::ThreadTaskTimings> {
55    Vec::new()
56}
57#[cfg(not(feature = "profiler"))]
58#[doc(hidden)]
59pub fn get_current_thread_timings(_included: TasksIncluded) -> gpui::ThreadTaskTimings {
60    gpui::ThreadTaskTimings {
61        thread_name: None,
62        thread_id: std::thread::current().id(),
63        timings: Vec::new(),
64        stats: TaskStatistics::default(),
65        total_pushed: 0,
66    }
67}
68#[cfg(not(feature = "profiler"))]
69#[doc(hidden)]
70pub fn take_all_stats(_included: TasksIncluded) -> Vec<gpui::ThreadTaskStatistics> {
71    Vec::new()
72}
73
74#[doc(hidden)]
75#[derive(Debug, Copy, Clone)]
76pub struct YieldTime(pub Instant);
77
78#[doc(hidden)]
79#[derive(Copy, Clone)]
80pub struct TaskTiming {
81    pub location: &'static core::panic::Location<'static>,
82    pub spawned: SpawnTime,
83    pub start: Instant,
84    pub end: YieldTime,
85}
86
87impl std::fmt::Debug for TaskTiming {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        f.debug_struct("TaskTiming")
90            .field("location", &self.location)
91            .field("since_spawned", &self.spawned.0.elapsed())
92            .field("last_poll_duration", &self.poll_duration())
93            .field("total_runtime", &self.since_spawn())
94            .finish()
95    }
96}
97
98#[doc(hidden)]
99#[derive(Debug, Copy, Clone)]
100pub struct ActiveTiming {
101    pub location: &'static core::panic::Location<'static>,
102    pub spawned: SpawnTime,
103    pub start: Instant,
104}
105
106impl TaskTiming {
107    /// A task timing with a duration of zero. Any task will replace this in history.
108    pub fn placeholder() -> Self {
109        let now = Instant::now();
110        Self {
111            location: std::panic::Location::caller(),
112            spawned: SpawnTime(now),
113            start: now,
114            end: YieldTime(now),
115        }
116    }
117
118    #[inline(always)]
119    pub fn poll_duration(&self) -> Duration {
120        self.end.0 - self.start
121    }
122
123    #[inline(always)]
124    fn since_spawn(&self) -> Duration {
125        self.end.0 - self.spawned.0
126    }
127}
128
129#[doc(hidden)]
130#[derive(Debug, Clone)]
131pub struct ThreadTaskTimings {
132    pub thread_name: Option<String>,
133    pub thread_id: ThreadId,
134    pub timings: Vec<TaskTiming>,
135    pub stats: TaskStatistics,
136    pub total_pushed: u64,
137}
138
139impl ThreadTaskTimings {
140    /// Convert upgraded per-thread timings into their structured format.
141    pub fn collect(
142        timings: Vec<(ThreadId, Arc<GuardedTaskTimings>)>,
143        included: TasksIncluded,
144    ) -> Vec<Self> {
145        timings
146            .into_iter()
147            .map(|(thread_id, timings)| {
148                let timings = timings.lock();
149                let thread_name = timings.thread_name.clone();
150                let total_pushed = timings.total_pushed;
151                let completed = &timings.timings;
152
153                let mut vec = Vec::with_capacity(completed.len() + 1); // +1 for running task
154                let (s1, s2) = completed.as_slices();
155                vec.extend_from_slice(s1);
156                vec.extend_from_slice(s2);
157                if let TasksIncluded::CompletedAndRunning = included
158                    && let Some(running) = timings.running
159                {
160                    vec.push(TaskTiming {
161                        location: running.location,
162                        spawned: running.spawned,
163                        start: running.start,
164                        end: YieldTime(Instant::now()),
165                    })
166                }
167
168                ThreadTaskTimings {
169                    thread_name,
170                    thread_id,
171                    timings: vec,
172                    stats: timings.stats.clone(),
173                    total_pushed,
174                }
175            })
176            .collect()
177    }
178}
179
180#[doc(hidden)]
181#[derive(Debug)]
182pub struct ThreadTaskStatistics {
183    pub thread_name: Option<String>,
184    pub thread_id: ThreadId,
185    pub stats: TaskStatistics,
186}
187
188impl ThreadTaskStatistics {
189    pub fn collect_and_reset(
190        timings: Vec<(ThreadId, Arc<GuardedTaskTimings>)>,
191        include_running: TasksIncluded,
192    ) -> Vec<Self> {
193        timings
194            .into_iter()
195            .map(|(thread_id, timings)| {
196                let mut timings = timings.lock();
197                let thread_name = timings.thread_name.clone();
198
199                let mut stats = std::mem::take(&mut timings.stats);
200                if let TasksIncluded::CompletedAndRunning = include_running
201                    && let Some(ActiveTiming {
202                        location,
203                        spawned,
204                        start,
205                    }) = timings.running
206                {
207                    let end = YieldTime(Instant::now());
208                    let timing = TaskTiming {
209                        location,
210                        spawned,
211                        start,
212                        end,
213                    };
214                    stats.add_runtime(timing);
215                    stats.add_yield_timing(timing);
216                }
217
218                Self {
219                    thread_name,
220                    thread_id,
221                    stats,
222                }
223            })
224            .collect()
225    }
226}
227
228/// Serializable variant of [`core::panic::Location`]
229#[derive(Debug, Clone, Serialize, Deserialize)]
230pub struct SerializedLocation {
231    /// Name of the source file
232    pub file: SharedString,
233    /// Line in the source file
234    pub line: u32,
235    /// Column in the source file
236    pub column: u32,
237}
238
239impl From<&core::panic::Location<'static>> for SerializedLocation {
240    fn from(value: &core::panic::Location<'static>) -> Self {
241        SerializedLocation {
242            file: value.file().into(),
243            line: value.line(),
244            column: value.column(),
245        }
246    }
247}
248
249/// Serializable variant of [`TaskTiming`]
250#[derive(Debug, Clone, Serialize, Deserialize)]
251pub struct SerializedTaskTiming {
252    /// Location of the timing
253    pub location: SerializedLocation,
254    /// Time at which the measurement was reported in nanoseconds
255    pub start: u128,
256    /// Duration of the measurement in nanoseconds
257    pub duration: u128,
258}
259
260impl SerializedTaskTiming {
261    /// Convert an array of [`TaskTiming`] into their serializable format
262    ///
263    /// # Params
264    ///
265    /// `anchor` - [`Instant`] that should be earlier than all timings to use as base anchor
266    pub fn convert(anchor: Instant, timings: &[TaskTiming]) -> Vec<SerializedTaskTiming> {
267        let serialized = timings
268            .iter()
269            .map(|timing| {
270                let start = timing.start.duration_since(anchor).as_nanos();
271                let duration = timing.end.0.duration_since(timing.start).as_nanos();
272                SerializedTaskTiming {
273                    location: timing.location.into(),
274                    start,
275                    duration,
276                }
277            })
278            .collect::<Vec<_>>();
279
280        serialized
281    }
282
283    /// `anchor` - [`Instant`] that should be earlier than all timings to use as base anchor
284    pub fn from(anchor: Instant, timing: TaskTiming) -> SerializedTaskTiming {
285        let start = timing.start.duration_since(anchor).as_nanos();
286        let duration = timing.end.0.duration_since(timing.start).as_nanos();
287        SerializedTaskTiming {
288            location: timing.location.into(),
289            start,
290            duration,
291        }
292    }
293}
294
295/// Serializable variant of [`ThreadTaskTimings`]
296#[derive(Debug, Clone, Serialize, Deserialize)]
297pub struct SerializedThreadTaskTimings {
298    /// Thread name
299    pub thread_name: Option<String>,
300    /// Hash of the thread id
301    pub thread_id: u64,
302    /// Timing records for this thread
303    pub timings: Vec<SerializedTaskTiming>,
304}
305
306impl SerializedThreadTaskTimings {
307    /// Convert [`ThreadTaskTimings`] into their serializable format
308    ///
309    /// # Params
310    ///
311    /// `anchor` - [`Instant`] that should be earlier than all timings to use as base anchor
312    pub fn convert(anchor: Instant, timings: ThreadTaskTimings) -> SerializedThreadTaskTimings {
313        let serialized_timings = SerializedTaskTiming::convert(anchor, &timings.timings);
314
315        let mut hasher = DefaultHasher::new();
316        timings.thread_id.hash(&mut hasher);
317        let thread_id = hasher.finish();
318
319        SerializedThreadTaskTimings {
320            thread_name: timings.thread_name,
321            thread_id,
322            timings: serialized_timings,
323        }
324    }
325}
326
327#[doc(hidden)]
328#[derive(Debug, Clone)]
329pub struct ThreadTimingsDelta {
330    /// Hashed thread id
331    pub thread_id: u64,
332    /// Thread name, if known
333    pub thread_name: Option<String>,
334    /// New timings since the last call. If the circular buffer wrapped around
335    /// since the previous poll, some entries may have been lost.
336    pub new_timings: Vec<SerializedTaskTiming>,
337}
338
339/// Tracks which timing events have already been seen so that callers can request only unseen events.
340#[doc(hidden)]
341pub struct ProfilingCollector {
342    startup_time: Instant,
343    cursors: HashMap<ThreadId, u64>,
344}
345
346impl ProfilingCollector {
347    pub fn new(startup_time: Instant) -> Self {
348        Self {
349            startup_time,
350            cursors: HashMap::default(),
351        }
352    }
353
354    pub fn startup_time(&self) -> Instant {
355        self.startup_time
356    }
357
358    pub fn collect_unseen(
359        &mut self,
360        all_timings: Vec<ThreadTaskTimings>,
361    ) -> Vec<ThreadTimingsDelta> {
362        let mut deltas = Vec::with_capacity(all_timings.len());
363
364        for thread in all_timings {
365            let mut hasher = DefaultHasher::new();
366            thread.thread_id.hash(&mut hasher);
367            let hashed_id = hasher.finish();
368
369            let prev_cursor = self.cursors.get(&thread.thread_id).copied().unwrap_or(0);
370            let buffer_len = thread.timings.len() as u64;
371            let buffer_start = thread.total_pushed.saturating_sub(buffer_len);
372
373            let slice = if prev_cursor < buffer_start {
374                // Cursor fell behind the buffer — some entries were evicted.
375                // Return everything still in the buffer.
376                thread.timings.as_slice()
377            } else {
378                let skip = (prev_cursor - buffer_start) as usize;
379                &thread.timings[skip.min(thread.timings.len())..]
380            };
381
382            let cursor_advance = thread.total_pushed;
383            self.cursors.insert(thread.thread_id, cursor_advance);
384
385            if slice.is_empty() {
386                continue;
387            }
388
389            let new_timings = SerializedTaskTiming::convert(self.startup_time, slice);
390
391            deltas.push(ThreadTimingsDelta {
392                thread_id: hashed_id,
393                thread_name: thread.thread_name,
394                new_timings,
395            });
396        }
397
398        deltas
399    }
400
401    pub fn reset(&mut self) {
402        self.cursors.clear();
403    }
404}
405
406// Allow 16MiB of task timing entries.
407// VecDeque grows by doubling its capacity when full, so keep this a power of 2 to avoid wasting
408// memory.
409#[cfg(feature = "profiler")]
410const MAX_TASK_TIMINGS: usize = (16 * 1024 * 1024) / core::mem::size_of::<TaskTiming>();
411
412#[doc(hidden)]
413pub(crate) type TaskTimings = VecDeque<TaskTiming>;
414
415#[doc(hidden)]
416pub type GuardedTaskTimings = spin::Mutex<ThreadTimings>;
417
418#[doc(hidden)]
419pub struct GlobalThreadTimings {
420    pub thread_id: ThreadId,
421    pub timings: std::sync::Weak<GuardedTaskTimings>,
422}
423
424#[doc(hidden)]
425#[derive(Debug, Clone)]
426pub struct TaskStatistics {
427    pub poll_time_to_beat: Duration,
428    pub runtime_to_beat: Duration,
429    pub longest_poll_times: [TaskTiming; 5],
430    pub longest_runtimes: [TaskTiming; 5],
431}
432
433impl std::fmt::Display for TaskStatistics {
434    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
435        f.write_str("Tasks that blocked the longest before yielding\n")?;
436        for timing in self.longest_poll_times {
437            f.write_fmt(format_args!(
438                "{:<20} - {}:{}\n",
439                format!("{:?}", timing.poll_duration()),
440                timing.location.file(),
441                timing.location.column()
442            ))?;
443        }
444        f.write_str("Tasks that ran the longest\n")?;
445        for timing in self.longest_runtimes {
446            f.write_fmt(format_args!(
447                "{:<20} - {}:{}\n",
448                format!("{:?}", timing.since_spawn()),
449                timing.location.file(),
450                timing.location.column()
451            ))?;
452        }
453        Ok(())
454    }
455}
456
457impl Default for TaskStatistics {
458    fn default() -> Self {
459        Self {
460            // Do not track polls that are not problematic
461            // this keeps more calls on the fast path
462            poll_time_to_beat: Duration::from_micros(100),
463            runtime_to_beat: Duration::from_micros(100),
464            longest_poll_times: [TaskTiming::placeholder(); 5],
465            longest_runtimes: [TaskTiming::placeholder(); 5],
466        }
467    }
468}
469
470impl TaskStatistics {
471    #[inline(always)]
472    fn add_yield_timing(&mut self, task: TaskTiming) {
473        let yielded_after = task.poll_duration();
474        if yielded_after >= self.poll_time_to_beat {
475            std::hint::cold_path(); // most tasks are not the worst, optimize for that
476            let to_replace = self
477                .longest_poll_times
478                .iter()
479                .position_min_by_key(|task| task.since_spawn())
480                .expect("guarded by the comparison with nth_longest_yield_time");
481            self.longest_poll_times[to_replace] = task;
482
483            self.poll_time_to_beat = self
484                .longest_poll_times
485                .iter()
486                .map(|task| task.since_spawn())
487                .min()
488                .expect("never empty");
489        }
490    }
491
492    #[inline(always)]
493    fn add_runtime(&mut self, task: TaskTiming) {
494        let runtime = task.since_spawn();
495        if runtime >= self.runtime_to_beat {
496            std::hint::cold_path(); // most tasks are not the worst, optimize for that
497            let to_replace = self
498                .longest_runtimes
499                .iter()
500                .position_min_by_key(|task| task.since_spawn())
501                .expect("guarded by the comparison with nth_longest_yield_time");
502            self.longest_runtimes[to_replace] = task;
503
504            self.runtime_to_beat = self
505                .longest_runtimes
506                .iter()
507                .map(|task| task.since_spawn())
508                .min()
509                .expect("never empty");
510        }
511    }
512}
513
514#[doc(hidden)]
515pub static GLOBAL_THREAD_TIMINGS: spin::Mutex<Vec<GlobalThreadTimings>> =
516    spin::Mutex::new(Vec::new());
517
518/// Upgrades all live per-thread timing handles, holding the global registry
519/// lock only for the duration of the upgrades.
520///
521/// The upgraded `Arc`s must never be dropped while `GLOBAL_THREAD_TIMINGS` is
522/// locked: dropping the last strong reference runs [`ThreadTimings::drop`],
523/// which locks `GLOBAL_THREAD_TIMINGS` again and would deadlock the
524/// non-reentrant spinlock. A thread exiting concurrently can hand off its last
525/// reference to us at any time, so callers of this function process (lock,
526/// read, drop) the returned handles only after the global lock is released.
527fn upgraded_thread_timings() -> Vec<(ThreadId, Arc<GuardedTaskTimings>)> {
528    let global_thread_timings = GLOBAL_THREAD_TIMINGS.lock();
529    global_thread_timings
530        .iter()
531        .filter_map(|t| Some((t.thread_id, t.timings.upgrade()?)))
532        .collect()
533}
534
535thread_local! {
536    #[doc(hidden)]
537    pub static THREAD_TIMINGS: LazyCell<Arc<GuardedTaskTimings>> = LazyCell::new(|| {
538        let current_thread = std::thread::current();
539        let thread_name = current_thread.name();
540        let thread_id = current_thread.id();
541        let timings = ThreadTimings::new(thread_name.map(|e| e.to_string()), thread_id);
542        let timings = Arc::new(spin::Mutex::new(timings));
543
544        {
545            let timings = Arc::downgrade(&timings);
546            let global_timings = GlobalThreadTimings {
547                thread_id: std::thread::current().id(),
548                timings,
549            };
550            GLOBAL_THREAD_TIMINGS.lock().push(global_timings);
551        }
552
553        timings
554    });
555}
556
557#[doc(hidden)]
558pub struct ThreadTimings {
559    pub thread_name: Option<String>,
560    pub thread_id: ThreadId,
561    pub timings: TaskTimings,
562    pub running: Option<ActiveTiming>,
563    pub stats: TaskStatistics,
564    pub total_pushed: u64,
565}
566
567impl ThreadTimings {
568    pub fn new(thread_name: Option<String>, thread_id: ThreadId) -> Self {
569        ThreadTimings {
570            thread_name,
571            thread_id,
572            timings: TaskTimings::new(),
573            stats: TaskStatistics::default(),
574            total_pushed: 0,
575            running: None,
576        }
577    }
578
579    #[cfg(feature = "profiler")]
580    pub fn update_running_task(
581        &mut self,
582        spawned: SpawnTime,
583        location: &'static std::panic::Location<'_>,
584    ) {
585        let start = Instant::now();
586        self.running = Some(ActiveTiming {
587            spawned,
588            location,
589            start,
590        });
591    }
592    #[cfg(not(feature = "profiler"))]
593    pub fn update_running_task(&mut self, _: SpawnTime, _: &'static std::panic::Location<'_>) {}
594
595    #[cfg(feature = "profiler")]
596    pub fn save_task_timing(&mut self, ended: YieldTime) -> TaskTiming {
597        let ActiveTiming {
598            location,
599            start,
600            spawned,
601        } = self
602            .running
603            .take()
604            .expect("this function is only ever called after register_task_start");
605
606        let timing = TaskTiming {
607            location,
608            spawned,
609            start,
610            end: ended,
611        };
612        self.stats.add_yield_timing(timing);
613        self.stats.add_runtime(timing);
614
615        if trace_enabled() {
616            std::hint::cold_path(); // optimize for when the profiling is off
617            if self.timings.len() >= MAX_TASK_TIMINGS {
618                self.timings.pop_front();
619            }
620            self.timings.push_back(timing);
621            self.total_pushed += 1;
622        }
623        timing
624    }
625    #[cfg(not(feature = "profiler"))]
626    pub fn save_task_timing(&mut self, _: YieldTime) {}
627
628    // Running tasks are included in the reliability trace, which is written
629    // whenever the foreground executor makes no progress for > n seconds
630    pub fn get_thread_task_timings(&self, includes: TasksIncluded) -> ThreadTaskTimings {
631        ThreadTaskTimings {
632            thread_name: self.thread_name.clone(),
633            thread_id: self.thread_id,
634            timings: self
635                .timings
636                .iter()
637                .cloned()
638                .chain(
639                    self.running
640                        .filter(|_| matches!(includes, TasksIncluded::CompletedAndRunning))
641                        .map(|running| TaskTiming {
642                            spawned: running.spawned,
643                            location: running.location,
644                            start: running.start,
645                            end: YieldTime(Instant::now()),
646                        }),
647                )
648                .collect(),
649            stats: self.stats.clone(),
650            total_pushed: self.total_pushed,
651        }
652    }
653}
654
655impl Drop for ThreadTimings {
656    fn drop(&mut self) {
657        let mut thread_timings = GLOBAL_THREAD_TIMINGS.lock();
658
659        let Some((index, _)) = thread_timings
660            .iter()
661            .enumerate()
662            .find(|(_, t)| t.thread_id == self.thread_id)
663        else {
664            return;
665        };
666        thread_timings.swap_remove(index);
667    }
668}
669
670#[doc(hidden)]
671pub fn update_running_task(spawned: SpawnTime, location: &'static std::panic::Location<'_>) {
672    #[cfg(feature = "profiler")]
673    journal::begin_foreground_turn();
674    THREAD_TIMINGS.with(|timings| {
675        timings.lock().update_running_task(spawned, location);
676    });
677}
678
679#[doc(hidden)]
680pub fn save_task_timing() {
681    let yielded_at = YieldTime(Instant::now());
682    #[cfg(feature = "profiler")]
683    {
684        let timing = THREAD_TIMINGS.with(|timings| timings.lock().save_task_timing(yielded_at));
685        journal::record_task_poll(timing);
686    }
687    #[cfg(not(feature = "profiler"))]
688    THREAD_TIMINGS.with(|timings| {
689        timings.lock().save_task_timing(yielded_at);
690    });
691}
692
693#[doc(hidden)]
694pub fn get_current_thread_task_timings(include_running: TasksIncluded) -> ThreadTaskTimings {
695    THREAD_TIMINGS.with(|timings| timings.lock().get_thread_task_timings(include_running))
696}
697
698const TRACE_SETTING_ENABLED: u64 = 1 << 63;
699const TRACE_SCOPE_COUNT_MASK: u64 = TRACE_SETTING_ENABLED - 1;
700static TRACE_STATE: AtomicU64 = AtomicU64::new(0);
701
702/// Enables or disables profiler trace collection at runtime.
703///
704/// When transitioning from enabled to disabled, `add_task_timing` becomes
705/// cheaper since only cheap statistics are gathered. The existing per-thread
706/// task buffers and the frame-event buffer are cleared so stale data isn't
707/// reported after a later re-enable. Active trace scopes keep collection enabled
708/// until the last scope ends. Calls with the current setting are a no-op.
709pub fn set_trace_enabled(enabled: bool) -> bool {
710    let mut state = TRACE_STATE.load(Ordering::Acquire);
711    loop {
712        let was_enabled = state & TRACE_SETTING_ENABLED != 0;
713        if was_enabled == enabled {
714            return false;
715        }
716
717        let next_state = if enabled {
718            state | TRACE_SETTING_ENABLED
719        } else {
720            state & TRACE_SCOPE_COUNT_MASK
721        };
722        match TRACE_STATE.compare_exchange_weak(
723            state,
724            next_state,
725            Ordering::AcqRel,
726            Ordering::Acquire,
727        ) {
728            Ok(_) => {
729                if next_state == 0 {
730                    clear_trace_buffers();
731                }
732                return true;
733            }
734            Err(updated_state) => state = updated_state,
735        }
736    }
737}
738
739#[cfg(any(feature = "bench-support", all(test, feature = "profiler")))]
740pub(crate) struct TraceGuard;
741
742#[cfg(any(feature = "bench-support", all(test, feature = "profiler")))]
743pub(crate) fn trace_scope() -> TraceGuard {
744    let incremented = TRACE_STATE.try_update(Ordering::AcqRel, Ordering::Acquire, |state| {
745        (state & TRACE_SCOPE_COUNT_MASK < TRACE_SCOPE_COUNT_MASK).then_some(state + 1)
746    });
747    assert!(incremented.is_ok(), "too many active profiler trace scopes");
748    TraceGuard
749}
750
751#[cfg(any(feature = "bench-support", all(test, feature = "profiler")))]
752impl Drop for TraceGuard {
753    fn drop(&mut self) {
754        let previous_state = TRACE_STATE.try_update(Ordering::AcqRel, Ordering::Acquire, |state| {
755            (state & TRACE_SCOPE_COUNT_MASK > 0).then_some(state - 1)
756        });
757        match previous_state {
758            Ok(1) => clear_trace_buffers(),
759            Ok(_) => {}
760            Err(_) => debug_assert!(false, "profiler trace scope count underflowed"),
761        }
762    }
763}
764
765/// Returns whether profiler trace collection is enabled.
766pub fn trace_enabled() -> bool {
767    TRACE_STATE.load(Ordering::Relaxed) != 0
768}
769
770fn clear_trace_buffers() {
771    for (_, timings) in upgraded_thread_timings() {
772        let mut timings = timings.lock();
773        timings.timings.clear();
774        timings.timings.shrink_to_fit();
775        timings.total_pushed = 0;
776    }
777    #[cfg(feature = "profiler")]
778    {
779        let mut frames = FRAME_TIMINGS.lock();
780        frames.timings.clear();
781        frames.timings.shrink_to_fit();
782        frames.total_pushed = 0;
783    }
784}
785
786/// Timing for a single drawn window frame.
787#[cfg(feature = "profiler")]
788#[derive(Debug, Copy, Clone)]
789pub struct FrameTiming {
790    /// The window that was drawn.
791    pub window_id: WindowId,
792    /// When the frame first became dirty (its first invalidation). `None` if
793    /// profiler tracing was not yet enabled when the invalidation occurred.
794    pub dirty_at: Option<Instant>,
795    /// Number of invalidations coalesced into this frame.
796    pub invalidations: u64,
797    /// When `Window::draw` started.
798    pub draw_start: Instant,
799    /// When `Window::draw` finished.
800    pub draw_end: Instant,
801    /// The refresh interval of the window's display when the frame was drawn,
802    /// or `None` when the platform doesn't report it.
803    pub refresh_interval: Option<Duration>,
804    /// When the platform's frame signal for this frame fired, or `None` when
805    /// the platform doesn't report it. Coalesced signals report the first.
806    pub signal_at: Option<Instant>,
807    /// How long each phase of the draw took.
808    pub phases: DrawPhases,
809}
810
811/// How long each phase of a window draw took.
812#[cfg(feature = "profiler")]
813#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
814pub struct DrawPhases {
815    /// Rendering views into elements and requesting their layout.
816    pub request_layout: Duration,
817    /// Computing layout and prepainting elements, including deferred draws,
818    /// prompts, drags, and tooltips.
819    pub prepaint: Duration,
820    /// Painting elements into the scene.
821    pub paint: Duration,
822}
823
824/// A phase of drawing a view.
825#[cfg(feature = "profiler")]
826#[derive(Debug, Copy, Clone, PartialEq, Eq)]
827pub enum ViewPhase {
828    /// Rendering the view and requesting its layout.
829    RequestLayout,
830    /// Prepainting the view's elements. Views whose cached elements are
831    /// stale also render and lay out here.
832    Prepaint,
833    /// Painting the view's elements.
834    Paint,
835}
836
837#[cfg(feature = "profiler")]
838impl ViewPhase {
839    /// The phase's name, e.g. `"prepaint"`.
840    pub fn as_str(self) -> &'static str {
841        match self {
842            Self::RequestLayout => "request_layout",
843            Self::Prepaint => "prepaint",
844            Self::Paint => "paint",
845        }
846    }
847}
848
849/// Views whose own work in one draw phase takes less than this aren't
850/// recorded, keeping the journal's per-frame cost bounded while still naming
851/// the views that make a frame late.
852#[cfg(feature = "profiler")]
853pub const VIEW_TIMING_FLOOR: Duration = Duration::from_micros(500);
854
855/// One phase of drawing one view, recorded when its own work took at least
856/// [`VIEW_TIMING_FLOOR`].
857#[cfg(feature = "profiler")]
858#[derive(Debug, Copy, Clone)]
859pub struct ViewTiming {
860    /// The view's type name.
861    pub name: &'static str,
862    /// The draw phase.
863    pub phase: ViewPhase,
864    /// When the view's phase began.
865    pub start: Instant,
866    /// When the view's phase ended.
867    pub end: Instant,
868    /// The phase's duration excluding views nested inside it, so a parent
869    /// view isn't blamed for its children's work.
870    pub self_duration: Duration,
871}
872
873/// The least work a frame can take before it counts as late: one refresh
874/// at 120 Hz. Frames rarely fit a single refresh on faster displays yet, so
875/// judging them by it would count nearly every frame as late and hide
876/// regressions; missed refreshes still measure against the real interval.
877#[cfg(feature = "profiler")]
878pub const FRAME_BUDGET_FLOOR: Duration = Duration::from_nanos(8_333_333);
879
880/// The work a frame can take before it counts as late when its display's
881/// refresh interval is unknown: one refresh at 60 Hz, the most common rate,
882/// so frames on faster displays may be judged leniently but none too strictly.
883#[cfg(feature = "profiler")]
884pub const UNKNOWN_REFRESH_FRAME_BUDGET: Duration = Duration::from_nanos(16_666_667);
885
886#[cfg(feature = "profiler")]
887impl FrameTiming {
888    /// When the frame's work began: the later of its signal and its first
889    /// invalidation, since waiting for the platform's frame signal isn't work,
890    /// however late it fires. `None` without a frame signal.
891    pub fn work_start(&self) -> Option<Instant> {
892        let signal_at = self.signal_at?;
893        // A frame signal can fire while the main thread is busy and only be
894        // handled after the window became dirty; time before then isn't the
895        // frame's.
896        Some(
897            self.dirty_at
898                .map_or(signal_at, |dirty_at| dirty_at.max(signal_at)),
899        )
900    }
901
902    /// The main-thread time from [`FrameTiming::work_start`] until the frame
903    /// was submitted at `submitted_at`: the start of its submission, which may
904    /// consist mostly of waiting for the display to free a buffer.
905    pub fn work(&self, submitted_at: Instant) -> Option<Duration> {
906        Some(submitted_at.saturating_duration_since(self.work_start()?))
907    }
908
909    /// Whether the frame's work, submitted at `submitted_at`, exceeded
910    /// [`FrameTiming::budget`], when its work is known.
911    pub fn is_late(&self, submitted_at: Instant) -> Option<bool> {
912        Some(self.work(submitted_at)? > self.budget())
913    }
914
915    /// The work a frame can take before it counts as late: one refresh
916    /// interval, but no less than [`FRAME_BUDGET_FLOOR`], or
917    /// [`UNKNOWN_REFRESH_FRAME_BUDGET`] when the interval is unknown.
918    pub fn budget(&self) -> Duration {
919        self.refresh_interval
920            .map_or(UNKNOWN_REFRESH_FRAME_BUDGET, |interval| {
921                interval.max(FRAME_BUDGET_FLOOR)
922            })
923    }
924
925    /// How many refreshes the frame missed when submitted at `submitted_at`:
926    /// zero when its work fit within one refresh interval.
927    pub fn missed_refreshes(&self, submitted_at: Instant) -> Option<u64> {
928        let refresh_interval = self.refresh_interval?;
929        let work = self.work(submitted_at)?;
930        let refreshes = work.as_nanos().div_ceil(refresh_interval.as_nanos()).max(1);
931        Some(u64::try_from(refreshes - 1).unwrap_or(u64::MAX))
932    }
933
934    /// Time spent inside `Window::draw`.
935    pub fn draw_duration(&self) -> Duration {
936        self.draw_end.duration_since(self.draw_start)
937    }
938
939    /// Time from the frame's first invalidation to the end of its draw, if the
940    /// first invalidation was observed.
941    pub fn dirty_to_draw_duration(&self) -> Option<Duration> {
942        self.dirty_at
943            .map(|dirty_at| self.draw_end.duration_since(dirty_at))
944    }
945}
946
947/// Work spent submitting a window frame to the platform.
948#[cfg(feature = "profiler")]
949#[derive(Debug, Copy, Clone)]
950pub struct PresentTiming {
951    /// The window whose frame was submitted.
952    pub window_id: WindowId,
953    /// When the platform submission began.
954    pub present_start: Instant,
955    /// When the platform submission completed.
956    pub present_end: Instant,
957    /// The interval since the previous animation frame was submitted, when
958    /// both belong to an active animation. Animation frames are newly drawn
959    /// frames and presents that only advance GPU scene animations.
960    pub animation_interval: Option<Duration>,
961}
962
963#[cfg(feature = "profiler")]
964impl PresentTiming {
965    /// Time spent submitting the frame to the platform.
966    pub fn present_duration(&self) -> Duration {
967        self.present_end.duration_since(self.present_start)
968    }
969}
970
971/// A frame event observed by the profiler.
972#[cfg(feature = "profiler")]
973#[derive(Debug, Copy, Clone)]
974pub enum FrameEvent {
975    /// A window frame was drawn.
976    Draw(FrameTiming),
977    /// A newly drawn window frame was presented.
978    Present(PresentTiming),
979}
980
981/// A point-in-time snapshot of the frame-duration histograms for a window,
982/// suitable for external formatting.
983#[cfg(feature = "profiler")]
984#[derive(Clone)]
985pub struct FrameDurationSnapshot {
986    /// Histogram of durations from the first invalidation through presentation, in nanoseconds.
987    pub dirty_to_present_histogram: Histogram<u64>,
988    /// Histogram of `Window::draw` durations, in nanoseconds.
989    pub draw_duration_histogram: Histogram<u64>,
990    /// Histogram of intervals between consecutively presented frames while the
991    /// window was animating, in nanoseconds.
992    pub present_interval_histogram: Histogram<u64>,
993    /// The same frames, split by the refresh interval of the window's display
994    /// when they were drawn.
995    pub by_refresh_interval: Vec<RefreshIntervalFrames>,
996}
997
998/// Upper bounds, in milliseconds, of the duration buckets in
999/// [`RefreshIntervalFrames`]. Each bucket counts values up to and including its
1000/// bound; a final bucket counts everything longer.
1001#[cfg(feature = "profiler")]
1002pub const FRAME_DURATION_BUCKETS_MS: [u64; 11] = [1, 2, 4, 8, 16, 33, 50, 100, 250, 500, 1000];
1003
1004/// Upper bounds, in percent of the display's real refresh interval, of the
1005/// work-per-frame buckets in [`RefreshIntervalFrames`]. Each bucket counts
1006/// values up to and including its bound; a final bucket counts everything
1007/// more. Whether a frame was on time is judged by [`FrameTiming::budget`]
1008/// instead, which never drops below [`FRAME_BUDGET_FLOOR`], so on displays
1009/// faster than 120 Hz frames above 100% can still be on time.
1010#[cfg(feature = "profiler")]
1011pub const FRAME_WORK_BUCKETS_PERCENT: [u64; 7] = [25, 50, 75, 100, 150, 200, 400];
1012
1013/// Counts `histogram`'s values above the previous bound and up to and
1014/// including each of `upper_bounds`, plus a final count of the values above
1015/// the last bound.
1016#[cfg(feature = "profiler")]
1017pub fn histogram_bucket_counts(
1018    histogram: &Histogram<u64>,
1019    upper_bounds: impl IntoIterator<Item = u64>,
1020) -> Vec<u64> {
1021    let mut counted = 0;
1022    let mut counts: Vec<u64> = upper_bounds
1023        .into_iter()
1024        .map(|bound| {
1025            // Cumulative counts, since adjacent bounds can share a histogram
1026            // bucket.
1027            let cumulative = histogram.count_between(0, bound);
1028            let count = cumulative.saturating_sub(counted);
1029            counted = counted.max(cumulative);
1030            count
1031        })
1032        .collect();
1033    counts.push(histogram.len().saturating_sub(counted));
1034    counts
1035}
1036
1037/// Statistics for the frames a window drew and presented while its display had
1038/// one refresh interval.
1039///
1040/// A frame is on time when its [`FrameTiming::work`] fit within
1041/// [`FrameTiming::budget`].
1042#[cfg(feature = "profiler")]
1043#[derive(Clone, Debug)]
1044pub struct RefreshIntervalFrames {
1045    /// The display's refresh interval, or `None` when the platform doesn't
1046    /// report it. Frame pacing is only measured for known intervals.
1047    pub refresh_interval: Option<Duration>,
1048    /// Frames drawn, whether or not they were presented.
1049    pub frames_drawn: u64,
1050    /// Draw durations, in nanoseconds.
1051    pub draw_duration: Histogram<u64>,
1052    /// Presented frames whose work fit within [`FrameTiming::budget`].
1053    pub frames_on_time: u64,
1054    /// Presented frames whose work exceeded [`FrameTiming::budget`].
1055    pub frames_late: u64,
1056    /// Refreshes that on-time and late frames missed in total, when the
1057    /// refresh interval is known.
1058    pub missed_refreshes: u64,
1059    /// Presented frames without a frame signal to measure their work from.
1060    pub frames_unmeasured: u64,
1061    /// Work of on-time and late frames, in nanoseconds.
1062    pub work: Histogram<u64>,
1063    /// Of `frames_on_time`, the frames that responded to input.
1064    pub input_frames_on_time: u64,
1065    /// Of `frames_late`, the frames that responded to input.
1066    pub input_frames_late: u64,
1067    /// Work of on-time and late frames that responded to input, in
1068    /// nanoseconds.
1069    pub input_work: Histogram<u64>,
1070}
1071
1072#[cfg(feature = "profiler")]
1073impl RefreshIntervalFrames {
1074    fn new(refresh_interval: Option<Duration>, empty_histogram: &Histogram<u64>) -> Self {
1075        Self {
1076            refresh_interval,
1077            frames_drawn: 0,
1078            draw_duration: empty_histogram.clone(),
1079            frames_on_time: 0,
1080            frames_late: 0,
1081            missed_refreshes: 0,
1082            frames_unmeasured: 0,
1083            work: empty_histogram.clone(),
1084            input_frames_on_time: 0,
1085            input_frames_late: 0,
1086            input_work: empty_histogram.clone(),
1087        }
1088    }
1089
1090    /// The frames recorded since `earlier`, a previous snapshot of the same
1091    /// statistics.
1092    pub fn since(&self, earlier: &Self) -> Self {
1093        let subtract = |current: &Histogram<u64>, earlier: &Histogram<u64>| {
1094            let mut delta = current.clone();
1095            match delta.subtract(earlier) {
1096                Ok(()) => delta,
1097                Err(error) => {
1098                    log::error!("failed to subtract frame histograms: {error}");
1099                    current.clone()
1100                }
1101            }
1102        };
1103        Self {
1104            refresh_interval: self.refresh_interval,
1105            frames_drawn: self.frames_drawn.saturating_sub(earlier.frames_drawn),
1106            draw_duration: subtract(&self.draw_duration, &earlier.draw_duration),
1107            frames_on_time: self.frames_on_time.saturating_sub(earlier.frames_on_time),
1108            frames_late: self.frames_late.saturating_sub(earlier.frames_late),
1109            missed_refreshes: self
1110                .missed_refreshes
1111                .saturating_sub(earlier.missed_refreshes),
1112            frames_unmeasured: self
1113                .frames_unmeasured
1114                .saturating_sub(earlier.frames_unmeasured),
1115            work: subtract(&self.work, &earlier.work),
1116            input_frames_on_time: self
1117                .input_frames_on_time
1118                .saturating_sub(earlier.input_frames_on_time),
1119            input_frames_late: self
1120                .input_frames_late
1121                .saturating_sub(earlier.input_frames_late),
1122            input_work: subtract(&self.input_work, &earlier.input_work),
1123        }
1124    }
1125
1126    fn record_presented_frame(
1127        &mut self,
1128        frame: &FrameTiming,
1129        presentation: &PresentTiming,
1130        responded_to_input: bool,
1131    ) {
1132        let submitted_at = presentation.present_start;
1133        let (Some(work), Some(is_late)) = (frame.work(submitted_at), frame.is_late(submitted_at))
1134        else {
1135            self.frames_unmeasured += 1;
1136            return;
1137        };
1138        record_duration(&mut self.work, work);
1139        if responded_to_input {
1140            record_duration(&mut self.input_work, work);
1141        }
1142        self.missed_refreshes += frame.missed_refreshes(submitted_at).unwrap_or(0);
1143        if is_late {
1144            self.frames_late += 1;
1145            self.input_frames_late += u64::from(responded_to_input);
1146        } else {
1147            self.frames_on_time += 1;
1148            self.input_frames_on_time += u64::from(responded_to_input);
1149        }
1150    }
1151}
1152
1153/// Records `duration` in nanoseconds, growing the histogram as needed.
1154#[cfg(feature = "profiler")]
1155fn record_duration(histogram: &mut Histogram<u64>, duration: Duration) {
1156    let nanos = u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX);
1157    if let Err(error) = histogram.record(nanos) {
1158        log::error!("failed to record frame duration: {error}");
1159    }
1160}
1161
1162/// A point-in-time snapshot of the input-latency histograms for a window,
1163/// suitable for external formatting.
1164#[cfg(feature = "profiler")]
1165#[derive(Clone)]
1166pub struct InputLatencySnapshot {
1167    /// Histogram of input-to-frame latency samples, in nanoseconds.
1168    pub latency_histogram: Histogram<u64>,
1169    /// Histogram of input events coalesced per rendered frame.
1170    pub events_per_frame_histogram: Histogram<u64>,
1171    /// Count of input events that arrived mid-draw and were excluded from
1172    /// latency recording.
1173    pub mid_draw_events_dropped: u64,
1174}
1175
1176#[cfg(feature = "profiler")]
1177enum WindowActivity {
1178    Input {
1179        started_at: Instant,
1180        kind: &'static str,
1181    },
1182    Draw {
1183        started_at: Instant,
1184    },
1185}
1186
1187/// Collects profiling information for one window.
1188///
1189/// Aggregate histograms are always populated when the `profiler` feature is
1190/// compiled in. Individual draw and present events are added to the global
1191/// profiler buffer only while tracing is enabled.
1192#[cfg(feature = "profiler")]
1193pub struct WindowProfiler {
1194    window_id: WindowId,
1195    active_activities: SmallVec<[WindowActivity; 4]>,
1196    active_actions: SmallVec<[(&'static str, Instant); 2]>,
1197    dirty_to_present_histogram: Histogram<u64>,
1198    draw_duration_histogram: Histogram<u64>,
1199    present_interval_histogram: Histogram<u64>,
1200    first_input_at: Option<Instant>,
1201    pending_input_count: u64,
1202    input_latency_histogram: Histogram<u64>,
1203    events_per_frame_histogram: Histogram<u64>,
1204    mid_draw_events_dropped: u64,
1205    last_present_at: Option<Instant>,
1206    animating_at_last_present: bool,
1207    throttled_since_present: bool,
1208    pending_frame: Option<FrameTiming>,
1209    refresh_interval: Option<Duration>,
1210    frame_signal_at: Option<Instant>,
1211    by_refresh_interval: Vec<RefreshIntervalFrames>,
1212    /// Cloned for each new refresh interval's histograms, since creating one
1213    /// can fail.
1214    empty_histogram: Histogram<u64>,
1215    draw_phases: DrawPhases,
1216    /// For each view phase in progress, the time spent in views nested
1217    /// inside it so far.
1218    nested_view_time: SmallVec<[Duration; 16]>,
1219}
1220
1221#[cfg(feature = "profiler")]
1222impl WindowProfiler {
1223    /// Creates a profiler for a window.
1224    pub fn new(window_id: WindowId) -> anyhow::Result<Self> {
1225        let profiler = Self {
1226            window_id,
1227            active_activities: SmallVec::new(),
1228            active_actions: SmallVec::new(),
1229            dirty_to_present_histogram: Histogram::new(3).map_err(|error| {
1230                anyhow::anyhow!("Failed to create dirty-to-present histogram: {error}")
1231            })?,
1232            draw_duration_histogram: Histogram::new(3).map_err(|error| {
1233                anyhow::anyhow!("Failed to create draw duration histogram: {error}")
1234            })?,
1235            present_interval_histogram: Histogram::new(3).map_err(|error| {
1236                anyhow::anyhow!("Failed to create present interval histogram: {error}")
1237            })?,
1238            first_input_at: None,
1239            pending_input_count: 0,
1240            input_latency_histogram: Histogram::new(3).map_err(|error| {
1241                anyhow::anyhow!("Failed to create input latency histogram: {error}")
1242            })?,
1243            events_per_frame_histogram: Histogram::new(3).map_err(|error| {
1244                anyhow::anyhow!("Failed to create events per frame histogram: {error}")
1245            })?,
1246            mid_draw_events_dropped: 0,
1247            last_present_at: None,
1248            animating_at_last_present: false,
1249            throttled_since_present: false,
1250            pending_frame: None,
1251            refresh_interval: None,
1252            frame_signal_at: None,
1253            by_refresh_interval: Vec::new(),
1254            empty_histogram: Histogram::new(3)
1255                .map_err(|error| anyhow::anyhow!("Failed to create frame histogram: {error}"))?,
1256            draw_phases: DrawPhases::default(),
1257            nested_view_time: SmallVec::new(),
1258        };
1259        journal::record_frame_pending(window_id, Instant::now());
1260        Ok(profiler)
1261    }
1262
1263    /// Records the beginning of an input dispatch. `kind` names the platform
1264    /// input variant being dispatched (see [`crate::PlatformInput::kind_name`]).
1265    pub fn begin_input(&mut self, kind: &'static str) {
1266        journal::begin_foreground_turn();
1267        self.active_activities.push(WindowActivity::Input {
1268            started_at: Instant::now(),
1269            kind,
1270        });
1271    }
1272
1273    /// Records the end of an input dispatch.
1274    pub fn end_input(&mut self, caused_invalidation: bool) {
1275        let Some(WindowActivity::Input { started_at, kind }) = self.active_activities.pop() else {
1276            debug_assert!(false, "input activity must be the current window activity");
1277            journal::end_foreground_turn();
1278            return;
1279        };
1280
1281        if !journal::power_interrupted_since(started_at) {
1282            journal::record_input(journal::InputTiming {
1283                kind,
1284                start: started_at,
1285                end: Instant::now(),
1286                caused_invalidation,
1287            });
1288        }
1289        journal::end_foreground_turn();
1290
1291        if !caused_invalidation || !journal::frame_sample_is_valid(self.window_id, started_at) {
1292            return;
1293        }
1294        if self
1295            .first_input_at
1296            .is_some_and(|at| !journal::frame_sample_is_valid(self.window_id, at))
1297        {
1298            self.first_input_at = None;
1299            self.pending_input_count = 0;
1300        }
1301
1302        let arrived_during_draw = self
1303            .active_activities
1304            .iter()
1305            .any(|activity| matches!(activity, WindowActivity::Draw { .. }));
1306        if arrived_during_draw {
1307            self.mid_draw_events_dropped += 1;
1308        } else {
1309            self.first_input_at.get_or_insert(started_at);
1310            self.pending_input_count += 1;
1311        }
1312    }
1313
1314    /// Records the beginning of an action handler.
1315    pub fn begin_action_handler(&mut self, action: &(dyn Action + 'static), cx: &mut App) {
1316        journal::begin_foreground_turn();
1317        let name = actions::update_running_action(action, cx);
1318        self.active_actions.push((name, Instant::now()));
1319    }
1320
1321    /// Records the end of the current action handler.
1322    pub fn end_action_handler(&mut self) {
1323        // Dual-write to the legacy aggregate store; its single global running
1324        // slot misbehaves when tests run actions concurrently, which is why
1325        // the journal entry is tracked here on the window instead.
1326        actions::save_action_timing();
1327        let Some((name, start)) = self.active_actions.pop() else {
1328            debug_assert!(false, "action handler must be begun before it ends");
1329            journal::end_foreground_turn();
1330            return;
1331        };
1332        if !journal::power_interrupted_since(start) {
1333            journal::record_action(ActionTiming {
1334                name,
1335                start,
1336                end: Instant::now(),
1337            });
1338        }
1339        journal::end_foreground_turn();
1340    }
1341
1342    /// Records that frame pacing deferred the pending frame, so its latency
1343    /// measures the frame rate limit and isn't recorded when it presents.
1344    pub fn record_frame_throttled(&mut self) {
1345        self.throttled_since_present = true;
1346    }
1347
1348    /// Records when the frame signal for the frame the next draw will produce
1349    /// fired. Coalesced signals report the first.
1350    pub fn record_frame_signal(&mut self, signal_at: Option<Instant>) {
1351        self.frame_signal_at = signal_at;
1352    }
1353
1354    /// Sets the refresh interval of the window's display, which frames drawn
1355    /// from now on are attributed to.
1356    pub fn set_refresh_interval(&mut self, refresh_interval: Option<Duration>) {
1357        self.refresh_interval = refresh_interval;
1358    }
1359
1360    /// Records the beginning of a window draw.
1361    pub fn begin_draw(&mut self) {
1362        journal::begin_foreground_turn();
1363        let started_at = Instant::now();
1364        journal::record_frame_pending(self.window_id, started_at);
1365        self.active_activities
1366            .push(WindowActivity::Draw { started_at });
1367    }
1368
1369    /// Records the phases of the window draw in progress.
1370    pub fn record_draw_phases(&mut self, phases: DrawPhases) {
1371        self.draw_phases = phases;
1372    }
1373
1374    /// Records the start of one phase of drawing a view, returning its start
1375    /// time to pass to [`WindowProfiler::end_view`].
1376    pub fn begin_view(&mut self) -> Instant {
1377        self.nested_view_time.push(Duration::ZERO);
1378        Instant::now()
1379    }
1380
1381    /// Records the end of a view phase begun at `start`, journaling it when
1382    /// its own work reached [`VIEW_TIMING_FLOOR`].
1383    pub fn end_view(&mut self, start: Instant, name: &'static str, phase: ViewPhase) {
1384        let end = Instant::now();
1385        let duration = end.saturating_duration_since(start);
1386        let nested = self.nested_view_time.pop().unwrap_or_default();
1387        if let Some(parent_nested) = self.nested_view_time.last_mut() {
1388            *parent_nested += duration;
1389        }
1390        let self_duration = duration.saturating_sub(nested);
1391        if self_duration >= VIEW_TIMING_FLOOR {
1392            journal::record_view(ViewTiming {
1393                name,
1394                phase,
1395                start,
1396                end,
1397                self_duration,
1398            });
1399        }
1400    }
1401
1402    /// Records the end of a window draw and returns the draw duration.
1403    pub fn end_draw(&mut self, dirty_at: Option<Instant>, invalidations: u64) -> Duration {
1404        let Some(WindowActivity::Draw {
1405            started_at: draw_start,
1406        }) = self.active_activities.pop()
1407        else {
1408            debug_assert!(false, "draw activity must be the current window activity");
1409            journal::end_foreground_turn();
1410            return Duration::ZERO;
1411        };
1412
1413        let draw_end = Instant::now();
1414        // Taken even when the draw isn't recorded, so a later draw can't claim it.
1415        let signal_at = self.frame_signal_at.take();
1416        let dirty_at = dirty_at.filter(|at| journal::frame_sample_is_valid(self.window_id, *at));
1417        let frame_timing = FrameTiming {
1418            window_id: self.window_id,
1419            dirty_at,
1420            invalidations,
1421            draw_start,
1422            draw_end,
1423            refresh_interval: self.refresh_interval,
1424            signal_at,
1425            phases: std::mem::take(&mut self.draw_phases),
1426        };
1427        let draw_duration = frame_timing.draw_duration();
1428        if !journal::power_interrupted_since(draw_start) {
1429            self.record_draw_timing(frame_timing);
1430        }
1431        journal::end_foreground_turn();
1432        draw_duration
1433    }
1434
1435    /// Records that a frame was presented.
1436    ///
1437    /// `next_frame_scheduled` marks the animation state for the interval
1438    /// ending at the next animation frame's presentation. `scene_animating`
1439    /// marks a present that advances GPU scene animations, which is an
1440    /// animation frame even when nothing was newly drawn.
1441    pub fn record_present(
1442        &mut self,
1443        present_start: Instant,
1444        present_end: Instant,
1445        window_active: bool,
1446        next_frame_scheduled: bool,
1447        scene_animating: bool,
1448    ) {
1449        self.record_present_at(
1450            present_start,
1451            present_end,
1452            window_active,
1453            next_frame_scheduled,
1454            scene_animating,
1455        );
1456    }
1457
1458    /// Returns a snapshot of the current input-latency histograms.
1459    pub fn input_latency_snapshot(&self) -> InputLatencySnapshot {
1460        InputLatencySnapshot {
1461            latency_histogram: self.input_latency_histogram.clone(),
1462            events_per_frame_histogram: self.events_per_frame_histogram.clone(),
1463            mid_draw_events_dropped: self.mid_draw_events_dropped,
1464        }
1465    }
1466
1467    /// Returns a snapshot of the current frame-duration histograms.
1468    pub fn frame_duration_snapshot(&self) -> FrameDurationSnapshot {
1469        FrameDurationSnapshot {
1470            dirty_to_present_histogram: self.dirty_to_present_histogram.clone(),
1471            draw_duration_histogram: self.draw_duration_histogram.clone(),
1472            present_interval_histogram: self.present_interval_histogram.clone(),
1473            by_refresh_interval: self.by_refresh_interval.clone(),
1474        }
1475    }
1476
1477    fn frames_for(&mut self, refresh_interval: Option<Duration>) -> &mut RefreshIntervalFrames {
1478        let index = match self
1479            .by_refresh_interval
1480            .iter()
1481            .position(|frames| frames.refresh_interval == refresh_interval)
1482        {
1483            Some(index) => index,
1484            None => {
1485                self.by_refresh_interval.push(RefreshIntervalFrames::new(
1486                    refresh_interval,
1487                    &self.empty_histogram,
1488                ));
1489                self.by_refresh_interval.len() - 1
1490            }
1491        };
1492        &mut self.by_refresh_interval[index]
1493    }
1494
1495    fn record_present_at(
1496        &mut self,
1497        present_start: Instant,
1498        present_end: Instant,
1499        window_active: bool,
1500        next_frame_scheduled: bool,
1501        scene_animating: bool,
1502    ) {
1503        let throttled = std::mem::take(&mut self.throttled_since_present);
1504        let mut responded_to_input = false;
1505        if let Some(first_input_at) = self.first_input_at.take()
1506            && !throttled
1507            && journal::frame_sample_is_valid(self.window_id, first_input_at)
1508        {
1509            responded_to_input = true;
1510            let latency_nanos = present_end.duration_since(first_input_at).as_nanos() as u64;
1511            self.input_latency_histogram.record(latency_nanos).ok();
1512            if self.pending_input_count > 0 {
1513                self.events_per_frame_histogram
1514                    .record(self.pending_input_count)
1515                    .ok();
1516            }
1517        }
1518        self.pending_input_count = 0;
1519
1520        let frame = self
1521            .pending_frame
1522            .take()
1523            .filter(|frame| journal::frame_sample_is_valid(self.window_id, frame.draw_start))
1524            .map(|mut frame| {
1525                frame.dirty_at = frame
1526                    .dirty_at
1527                    .filter(|at| !throttled && journal::frame_sample_is_valid(self.window_id, *at));
1528                frame
1529            });
1530        let is_animation_frame = frame.is_some() || scene_animating;
1531        let animation_interval =
1532            if is_animation_frame && self.animating_at_last_present && window_active {
1533                self.last_present_at
1534                    .filter(|at| journal::frame_sample_is_valid(self.window_id, *at))
1535                    .map(|last_present_at| present_end.duration_since(last_present_at))
1536            } else {
1537                None
1538            };
1539        let present_timing = PresentTiming {
1540            window_id: self.window_id,
1541            present_start,
1542            present_end,
1543            animation_interval,
1544        };
1545        journal::record_present(present_timing, frame);
1546
1547        if is_animation_frame {
1548            if let Some(animation_interval) = animation_interval {
1549                self.present_interval_histogram
1550                    .record(animation_interval.as_nanos() as u64)
1551                    .ok();
1552            }
1553            self.last_present_at = Some(present_end);
1554            self.animating_at_last_present = next_frame_scheduled && window_active;
1555        }
1556
1557        let Some(frame) = frame else {
1558            return;
1559        };
1560        self.frames_for(frame.refresh_interval)
1561            .record_presented_frame(&frame, &present_timing, responded_to_input);
1562
1563        if let Some(dirty_at) = frame.dirty_at
1564            && let Err(error) = self
1565                .dirty_to_present_histogram
1566                .record(present_end.duration_since(dirty_at).as_nanos() as u64)
1567        {
1568            log::error!("failed to record dirty-to-present frame timing: {error}");
1569        }
1570        record_frame_event(FrameEvent::Present(present_timing));
1571    }
1572
1573    fn record_draw_timing(&mut self, timing: FrameTiming) {
1574        self.record_draw_duration(timing.draw_duration());
1575        let frames = self.frames_for(timing.refresh_interval);
1576        frames.frames_drawn += 1;
1577        record_duration(&mut frames.draw_duration, timing.draw_duration());
1578        self.pending_frame = Some(timing);
1579        record_frame_event(FrameEvent::Draw(timing));
1580        journal::record_draw(timing);
1581    }
1582
1583    fn record_draw_duration(&mut self, duration: Duration) {
1584        self.draw_duration_histogram
1585            .record(duration.as_nanos() as u64)
1586            .ok();
1587    }
1588}
1589
1590#[cfg(feature = "profiler")]
1591impl Drop for WindowProfiler {
1592    fn drop(&mut self) {
1593        journal::record_window_closed(self.window_id);
1594    }
1595}
1596
1597// Allow 16MiB of frame event entries.
1598#[cfg(feature = "profiler")]
1599const MAX_FRAME_TIMINGS: usize = (16 * 1024 * 1024) / core::mem::size_of::<FrameEvent>();
1600
1601#[cfg(feature = "profiler")]
1602struct FrameTimings {
1603    timings: VecDeque<FrameEvent>,
1604    total_pushed: u64,
1605}
1606
1607#[cfg(feature = "profiler")]
1608static FRAME_TIMINGS: spin::Mutex<FrameTimings> = spin::Mutex::new(FrameTimings {
1609    timings: VecDeque::new(),
1610    total_pushed: 0,
1611});
1612
1613/// Records a frame event.
1614///
1615/// No-op unless profiler tracing is enabled via [`set_trace_enabled`].
1616#[cfg(feature = "profiler")]
1617pub fn record_frame_event(event: FrameEvent) {
1618    if !trace_enabled() {
1619        return;
1620    }
1621    std::hint::cold_path(); // optimize for when profiling is off
1622
1623    let mut frames = FRAME_TIMINGS.lock();
1624    if frames.timings.len() >= MAX_FRAME_TIMINGS {
1625        frames.timings.pop_front();
1626    }
1627    frames.timings.push_back(event);
1628    frames.total_pushed += 1;
1629}
1630
1631/// Drains frame events recorded after this collector was created, tracking a
1632/// cursor so each call to [`Self::collect_unseen`] returns only new entries.
1633#[cfg(feature = "profiler")]
1634pub struct FrameTimingCollector {
1635    cursor: u64,
1636}
1637
1638#[cfg(feature = "profiler")]
1639impl Default for FrameTimingCollector {
1640    fn default() -> Self {
1641        Self::new()
1642    }
1643}
1644
1645#[cfg(feature = "profiler")]
1646impl FrameTimingCollector {
1647    /// Creates a collector that only sees frame events recorded from this point on.
1648    pub fn new() -> Self {
1649        Self {
1650            cursor: FRAME_TIMINGS.lock().total_pushed,
1651        }
1652    }
1653
1654    /// Returns frame events recorded since the previous call (or since the
1655    /// collector was created). If the ring buffer wrapped around since the
1656    /// previous poll, the evicted entries are lost.
1657    pub fn collect_unseen(&mut self) -> Vec<FrameEvent> {
1658        let frames = FRAME_TIMINGS.lock();
1659        let buffer_len = frames.timings.len() as u64;
1660        let buffer_start = frames.total_pushed.saturating_sub(buffer_len);
1661        let skip = self.cursor.saturating_sub(buffer_start) as usize;
1662        let unseen = frames
1663            .timings
1664            .iter()
1665            .skip(skip.min(frames.timings.len()))
1666            .copied()
1667            .collect();
1668        self.cursor = frames.total_pushed;
1669        unseen
1670    }
1671}
1672
1673#[cfg(all(test, feature = "profiler"))]
1674mod tests {
1675    use super::*;
1676    use std::sync::{Mutex, MutexGuard};
1677
1678    #[test]
1679    fn interruptions_drop_latency_samples_but_hiding_keeps_draw_work() {
1680        for sleep in [false, true] {
1681            let (_journal, _guard) = journal::install_test_foreground_journal(64, 4);
1682            let id = WindowId::from(1);
1683            let mut profiler = WindowProfiler::new(id).expect("valid histograms");
1684            let old = Instant::now() - Duration::from_secs(1);
1685            record_test_draw(&mut profiler, old);
1686            profiler.record_present_at(old, old, true, true, false);
1687            profiler.first_input_at = Some(old);
1688            profiler.pending_input_count = 1;
1689            profiler.begin_draw();
1690            if sleep {
1691                journal::record_power_transition(journal::PowerState::Suspended);
1692                journal::record_power_transition(journal::PowerState::Awake);
1693            } else {
1694                journal::record_window_visibility(id, crate::WindowVisibility::Hidden);
1695                journal::record_window_visibility(id, crate::WindowVisibility::Visible);
1696            }
1697            profiler.end_draw(Some(old), 1);
1698            let now = Instant::now();
1699            profiler.record_present_at(now, now, true, true, false);
1700            assert_eq!(
1701                profiler.draw_duration_histogram.len(),
1702                if sleep { 1 } else { 2 }
1703            );
1704            assert_eq!(profiler.input_latency_histogram.len(), 0);
1705            assert_eq!(profiler.dirty_to_present_histogram.len(), 1);
1706            assert_eq!(profiler.present_interval_histogram.len(), 0);
1707            profiler.begin_draw();
1708            profiler.end_draw(Some(Instant::now()), 1);
1709            let now = Instant::now();
1710            profiler.record_present_at(now, now, true, true, false);
1711            assert_eq!(profiler.dirty_to_present_histogram.len(), 2);
1712        }
1713    }
1714
1715    #[test]
1716    fn frame_work_starts_at_the_later_of_signal_and_invalidation() {
1717        let refresh = Duration::from_millis(10);
1718        let start = Instant::now();
1719        let at = |ms| start + Duration::from_millis(ms);
1720        let frame_with = |dirty: Option<u64>, signal: Option<u64>| FrameTiming {
1721            window_id: WindowId::from(1),
1722            dirty_at: dirty.map(at),
1723            invalidations: 1,
1724            draw_start: at(1),
1725            draw_end: at(2),
1726            refresh_interval: Some(refresh),
1727            signal_at: signal.map(at),
1728            phases: Default::default(),
1729        };
1730        let work = |dirty, signal| frame_with(dirty, signal).work(at(50));
1731
1732        // Waiting for the frame signal isn't work, however late it fires.
1733        assert_eq!(work(Some(0), Some(8)), Some(Duration::from_millis(42)));
1734        assert_eq!(work(Some(0), Some(40)), Some(Duration::from_millis(10)));
1735        // A frame needed after its signal fired is measured from when it was
1736        // needed.
1737        assert_eq!(work(Some(5), Some(0)), Some(Duration::from_millis(45)));
1738        // Animation frames have no invalidation to wait for.
1739        assert_eq!(work(None, Some(0)), Some(Duration::from_millis(50)));
1740        assert_eq!(work(Some(0), None), None);
1741
1742        let frame = frame_with(Some(0), Some(0));
1743        for (submitted_ms, missed) in [(7, 0), (10, 0), (20, 1), (25, 2)] {
1744            assert_eq!(frame.missed_refreshes(at(submitted_ms)), Some(missed));
1745        }
1746    }
1747
1748    #[test]
1749    fn frames_are_split_by_refresh_interval_and_classified() {
1750        let (_journal, _guard) = journal::install_test_foreground_journal(64, 4);
1751        let mut profiler = WindowProfiler::new(WindowId::from(1)).expect("valid histograms");
1752        let sixty_hertz = Duration::from_secs(1) / 60;
1753        let one_hundred_twenty_hertz = Duration::from_secs(1) / 120;
1754        let three_hundred_sixty_hertz = Duration::from_secs(1) / 360;
1755        let base = Instant::now();
1756        let at = |ms| base + Duration::from_millis(ms);
1757
1758        struct Frame {
1759            refresh_interval: Option<Duration>,
1760            signal_ms: Option<u64>,
1761            present_start_ms: u64,
1762            responded_to_input: bool,
1763        }
1764        let frames = [
1765            // On time, responding to input.
1766            Frame {
1767                refresh_interval: Some(sixty_hertz),
1768                signal_ms: Some(1),
1769                present_start_ms: 5,
1770                responded_to_input: true,
1771            },
1772            Frame {
1773                refresh_interval: Some(sixty_hertz),
1774                signal_ms: Some(0),
1775                present_start_ms: 40,
1776                responded_to_input: true,
1777            },
1778            Frame {
1779                refresh_interval: Some(sixty_hertz),
1780                signal_ms: None,
1781                present_start_ms: 5,
1782                responded_to_input: false,
1783            },
1784            // A late frame signal: only the 2 ms after it count.
1785            Frame {
1786                refresh_interval: Some(sixty_hertz),
1787                signal_ms: Some(40),
1788                present_start_ms: 42,
1789                responded_to_input: false,
1790            },
1791            Frame {
1792                refresh_interval: Some(one_hundred_twenty_hertz),
1793                signal_ms: Some(0),
1794                present_start_ms: 12,
1795                responded_to_input: false,
1796            },
1797            // Misses refreshes but fits the budget floor.
1798            Frame {
1799                refresh_interval: Some(three_hundred_sixty_hertz),
1800                signal_ms: Some(0),
1801                present_start_ms: 6,
1802                responded_to_input: false,
1803            },
1804            Frame {
1805                refresh_interval: Some(three_hundred_sixty_hertz),
1806                signal_ms: Some(0),
1807                present_start_ms: 9,
1808                responded_to_input: false,
1809            },
1810            Frame {
1811                refresh_interval: None,
1812                signal_ms: Some(0),
1813                present_start_ms: 2,
1814                responded_to_input: false,
1815            },
1816        ];
1817        for frame in frames {
1818            profiler.set_refresh_interval(frame.refresh_interval);
1819            profiler.record_draw_timing(FrameTiming {
1820                window_id: profiler.window_id,
1821                dirty_at: Some(at(0)),
1822                invalidations: 1,
1823                draw_start: at(0),
1824                draw_end: at(1),
1825                refresh_interval: frame.refresh_interval,
1826                signal_at: frame.signal_ms.map(at),
1827                phases: Default::default(),
1828            });
1829            if frame.responded_to_input {
1830                profiler.first_input_at = Some(at(0));
1831            }
1832            profiler.record_present_at(
1833                at(frame.present_start_ms),
1834                at(frame.present_start_ms + 1),
1835                true,
1836                false,
1837                false,
1838            );
1839        }
1840
1841        let snapshot = profiler.frame_duration_snapshot();
1842        let frames_for = |refresh_interval| {
1843            snapshot
1844                .by_refresh_interval
1845                .iter()
1846                .find(|frames| frames.refresh_interval == refresh_interval)
1847                .cloned()
1848                .expect("frames for the refresh interval")
1849        };
1850        let work_buckets = |work: &Histogram<u64>, refresh_interval: Duration| {
1851            histogram_bucket_counts(
1852                work,
1853                FRAME_WORK_BUCKETS_PERCENT
1854                    .map(|percent| (refresh_interval * percent as u32 / 100).as_nanos() as u64),
1855            )
1856        };
1857        let sixty = frames_for(Some(sixty_hertz));
1858        assert_eq!(sixty.frames_drawn, 4);
1859        assert_eq!(sixty.frames_on_time, 2);
1860        assert_eq!(sixty.frames_late, 1);
1861        // 40 ms of work at 16.7 ms per refresh.
1862        assert_eq!(sixty.missed_refreshes, 2);
1863        assert_eq!(sixty.frames_unmeasured, 1);
1864        assert_eq!(
1865            work_buckets(&sixty.work, sixty_hertz),
1866            [2, 0, 0, 0, 0, 0, 1, 0]
1867        );
1868        assert_eq!(sixty.input_frames_on_time, 1);
1869        assert_eq!(sixty.input_frames_late, 1);
1870        assert_eq!(
1871            work_buckets(&sixty.input_work, sixty_hertz),
1872            [1, 0, 0, 0, 0, 0, 1, 0]
1873        );
1874
1875        let one_hundred_twenty = frames_for(Some(one_hundred_twenty_hertz));
1876        assert_eq!(one_hundred_twenty.frames_late, 1);
1877        assert_eq!(one_hundred_twenty.missed_refreshes, 1);
1878        assert_eq!(one_hundred_twenty.input_frames_late, 0);
1879
1880        let three_hundred_sixty = frames_for(Some(three_hundred_sixty_hertz));
1881        assert_eq!(three_hundred_sixty.frames_on_time, 1);
1882        assert_eq!(three_hundred_sixty.frames_late, 1);
1883        // 6 ms of work misses 2 refreshes at 2.78 ms each, and 9 ms misses 3.
1884        assert_eq!(three_hundred_sixty.missed_refreshes, 5);
1885
1886        // Judged against the 60 Hz budget, without missed refreshes.
1887        let unknown = frames_for(None);
1888        assert_eq!(unknown.frames_drawn, 1);
1889        assert_eq!(unknown.frames_on_time, 1);
1890        assert_eq!(unknown.missed_refreshes, 0);
1891
1892        let later = profiler.frame_duration_snapshot();
1893        let delta = later.by_refresh_interval[0].since(&snapshot.by_refresh_interval[0]);
1894        assert_eq!(
1895            delta.frames_drawn + delta.frames_on_time + delta.frames_late,
1896            0
1897        );
1898        assert_eq!(
1899            delta.draw_duration.len() + delta.work.len() + delta.input_work.len(),
1900            0
1901        );
1902    }
1903
1904    #[test]
1905    fn records_draw_events_only_while_tracing() {
1906        let _trace_test_guard = TraceTestGuard::new();
1907        let window_id = WindowId::from(0xD0A0);
1908        let mut window_profiler =
1909            WindowProfiler::new(window_id).expect("window profiler should initialize");
1910        let dirty_at = Instant::now();
1911        let mut collector = FrameTimingCollector::new();
1912
1913        window_profiler.begin_draw();
1914        window_profiler.end_draw(Some(dirty_at), 3);
1915        assert!(
1916            collector
1917                .collect_unseen()
1918                .iter()
1919                .all(|event| !event_matches_window(*event, window_id))
1920        );
1921
1922        set_trace_enabled(true);
1923        let mut collector = FrameTimingCollector::new();
1924        window_profiler.begin_draw();
1925        window_profiler.end_draw(Some(dirty_at), 3);
1926
1927        let timing = collector
1928            .collect_unseen()
1929            .into_iter()
1930            .find_map(|event| match event {
1931                FrameEvent::Draw(timing) if timing.window_id == window_id => Some(timing),
1932                _ => None,
1933            })
1934            .expect("draw event should be recorded while tracing");
1935        assert_eq!(timing.dirty_at, Some(dirty_at));
1936        assert_eq!(timing.invalidations, 3);
1937        assert!(timing.draw_start >= dirty_at);
1938    }
1939
1940    #[test]
1941    fn records_present_events_for_newly_drawn_frames() {
1942        let _trace_test_guard = TraceTestGuard::new();
1943        set_trace_enabled(true);
1944        let window_id = WindowId::from(0xA11E);
1945        let mut window_profiler =
1946            WindowProfiler::new(window_id).expect("window profiler should initialize");
1947        let start = Instant::now();
1948        let mut collector = FrameTimingCollector::new();
1949
1950        record_test_draw(&mut window_profiler, start);
1951        window_profiler.record_present_at(start, start, true, true, false);
1952        record_test_draw(&mut window_profiler, start + FRAME);
1953        window_profiler.record_present_at(start + FRAME, start + FRAME, true, true, false);
1954        window_profiler.record_present_at(
1955            start + FRAME + FRAME / 2,
1956            start + FRAME + FRAME / 2,
1957            true,
1958            true,
1959            false,
1960        );
1961
1962        let present_timings = collector
1963            .collect_unseen()
1964            .into_iter()
1965            .filter_map(|event| match event {
1966                FrameEvent::Present(timing) if timing.window_id == window_id => Some(timing),
1967                _ => None,
1968            })
1969            .collect::<Vec<_>>();
1970        let [first_present, second_present] = present_timings.as_slice() else {
1971            panic!("expected exactly two present events, got {present_timings:?}");
1972        };
1973        assert_eq!(first_present.animation_interval, None);
1974        assert_eq!(second_present.animation_interval, Some(FRAME));
1975
1976        #[cfg(feature = "profiler")]
1977        {
1978            assert_eq!(window_profiler.present_interval_histogram.len(), 1);
1979            assert!(
1980                window_profiler.present_interval_histogram.max()
1981                    >= second_present
1982                        .animation_interval
1983                        .expect("second present should have an animation interval")
1984                        .as_nanos() as u64
1985            );
1986        }
1987    }
1988
1989    #[test]
1990    fn disabling_tracing_clears_frame_events() {
1991        let _trace_test_guard = TraceTestGuard::new();
1992        set_trace_enabled(true);
1993        let window_id = WindowId::from(0xC1EA);
1994        let mut window_profiler =
1995            WindowProfiler::new(window_id).expect("window profiler should initialize");
1996        let mut collector = FrameTimingCollector::new();
1997
1998        window_profiler.begin_draw();
1999        window_profiler.end_draw(None, 0);
2000        assert!(
2001            FRAME_TIMINGS
2002                .lock()
2003                .timings
2004                .iter()
2005                .copied()
2006                .any(|event| event_matches_window(event, window_id))
2007        );
2008
2009        set_trace_enabled(false);
2010        assert!(
2011            collector
2012                .collect_unseen()
2013                .iter()
2014                .all(|event| !event_matches_window(*event, window_id))
2015        );
2016    }
2017
2018    #[cfg(feature = "profiler")]
2019    #[test]
2020    fn records_intervals_only_between_animation_frames() {
2021        let mut window_profiler =
2022            WindowProfiler::new(WindowId::from(1)).expect("window profiler should initialize");
2023        let start = Instant::now();
2024
2025        draw_and_present(&mut window_profiler, start, true, true);
2026        assert_eq!(window_profiler.present_interval_histogram.len(), 0);
2027
2028        draw_and_present(&mut window_profiler, start + FRAME, true, true);
2029        assert_eq!(window_profiler.present_interval_histogram.len(), 1);
2030
2031        draw_and_present(&mut window_profiler, start + FRAME * 2, true, false);
2032        assert_eq!(window_profiler.present_interval_histogram.len(), 2);
2033
2034        draw_and_present(&mut window_profiler, start + FRAME * 100, true, true);
2035        assert_eq!(window_profiler.present_interval_histogram.len(), 2);
2036    }
2037
2038    #[cfg(feature = "profiler")]
2039    #[test]
2040    fn missed_frames_stretch_the_recorded_interval() {
2041        let mut window_profiler =
2042            WindowProfiler::new(WindowId::from(2)).expect("window profiler should initialize");
2043        let start = Instant::now();
2044
2045        draw_and_present(&mut window_profiler, start, true, true);
2046        draw_and_present(&mut window_profiler, start + FRAME * 5, true, true);
2047
2048        let recorded = window_profiler.present_interval_histogram.max();
2049        assert!(recorded >= (FRAME * 4).as_nanos() as u64);
2050    }
2051
2052    #[cfg(feature = "profiler")]
2053    #[test]
2054    fn ignores_re_presents_of_unchanged_frames() {
2055        let mut window_profiler =
2056            WindowProfiler::new(WindowId::from(3)).expect("window profiler should initialize");
2057        let start = Instant::now();
2058
2059        draw_and_present(&mut window_profiler, start, true, true);
2060        window_profiler.record_present_at(start + FRAME / 2, start + FRAME / 2, true, true, false);
2061        draw_and_present(&mut window_profiler, start + FRAME, true, true);
2062
2063        assert_eq!(window_profiler.present_interval_histogram.len(), 1);
2064        assert!(
2065            window_profiler.present_interval_histogram.max() >= (FRAME * 3 / 4).as_nanos() as u64
2066        );
2067    }
2068
2069    #[test]
2070    fn records_intervals_between_presents_of_gpu_scene_animations() {
2071        let mut window_profiler =
2072            WindowProfiler::new(WindowId::from(10)).expect("window profiler should initialize");
2073        let start = Instant::now();
2074
2075        draw_and_present(&mut window_profiler, start, true, true);
2076        // Frames that only advance GPU animations present without drawing.
2077        for frame in 1..=3 {
2078            let presented_at = start + FRAME * frame;
2079            window_profiler.record_present_at(presented_at, presented_at, true, true, true);
2080        }
2081        assert_eq!(window_profiler.present_interval_histogram.len(), 3);
2082        assert!(window_profiler.present_interval_histogram.max() < (FRAME * 2).as_nanos() as u64);
2083
2084        // The last animation frame ends the animation.
2085        let presented_at = start + FRAME * 4;
2086        window_profiler.record_present_at(presented_at, presented_at, true, false, true);
2087        let presented_at = start + FRAME * 50;
2088        window_profiler.record_present_at(presented_at, presented_at, true, true, true);
2089        assert_eq!(window_profiler.present_interval_histogram.len(), 4);
2090    }
2091
2092    #[cfg(feature = "profiler")]
2093    #[test]
2094    fn skips_intervals_for_inactive_windows() {
2095        let mut window_profiler =
2096            WindowProfiler::new(WindowId::from(4)).expect("window profiler should initialize");
2097        let start = Instant::now();
2098
2099        draw_and_present(&mut window_profiler, start, false, true);
2100        draw_and_present(&mut window_profiler, start + FRAME, false, true);
2101        assert_eq!(window_profiler.present_interval_histogram.len(), 0);
2102
2103        draw_and_present(&mut window_profiler, start + FRAME * 2, true, true);
2104        assert_eq!(window_profiler.present_interval_histogram.len(), 0);
2105
2106        draw_and_present(&mut window_profiler, start + FRAME * 3, true, true);
2107        assert_eq!(window_profiler.present_interval_histogram.len(), 1);
2108    }
2109
2110    #[test]
2111    fn records_dirty_to_present_durations() {
2112        let mut window_profiler =
2113            WindowProfiler::new(WindowId::from(8)).expect("window profiler should initialize");
2114        let draw_end = Instant::now();
2115        let present_end = draw_end + Duration::from_millis(6);
2116
2117        record_test_draw(&mut window_profiler, draw_end);
2118        window_profiler.record_present_at(present_end, present_end, true, false, false);
2119
2120        let snapshot = window_profiler.frame_duration_snapshot();
2121        let histogram = snapshot.dirty_to_present_histogram;
2122        assert_eq!(histogram.len(), 1);
2123        assert!(histogram.max() >= Duration::from_millis(10).as_nanos() as u64);
2124    }
2125
2126    #[cfg(feature = "profiler")]
2127    #[test]
2128    fn records_every_draw_duration() {
2129        let mut window_profiler =
2130            WindowProfiler::new(WindowId::from(5)).expect("window profiler should initialize");
2131
2132        window_profiler.record_draw_duration(Duration::from_millis(2));
2133        window_profiler.record_draw_duration(Duration::from_millis(40));
2134
2135        let snapshot = window_profiler.frame_duration_snapshot();
2136        assert_eq!(snapshot.draw_duration_histogram.len(), 2);
2137        assert!(snapshot.draw_duration_histogram.max() >= 39_000_000);
2138    }
2139
2140    #[test]
2141    fn records_input_latency_at_the_frame_presentation_timestamp() {
2142        let mut window_profiler =
2143            WindowProfiler::new(WindowId::from(6)).expect("window profiler should initialize");
2144        let first_input_at = Instant::now();
2145        let presented_at = first_input_at + Duration::from_millis(12);
2146
2147        begin_input_at(&mut window_profiler, first_input_at);
2148        window_profiler.end_input(true);
2149        begin_input_at(
2150            &mut window_profiler,
2151            first_input_at + Duration::from_millis(2),
2152        );
2153        window_profiler.end_input(true);
2154        record_test_draw(&mut window_profiler, presented_at);
2155        window_profiler.record_present_at(presented_at, presented_at, true, false, false);
2156
2157        let snapshot = window_profiler.input_latency_snapshot();
2158        assert_eq!(snapshot.latency_histogram.len(), 1);
2159        assert!(snapshot.latency_histogram.max() >= Duration::from_millis(12).as_nanos() as u64);
2160        assert_eq!(snapshot.events_per_frame_histogram.len(), 1);
2161        assert_eq!(snapshot.events_per_frame_histogram.max(), 2);
2162        assert_eq!(snapshot.mid_draw_events_dropped, 0);
2163    }
2164
2165    #[test]
2166    fn excludes_input_that_arrives_during_a_draw() {
2167        let mut window_profiler =
2168            WindowProfiler::new(WindowId::from(7)).expect("window profiler should initialize");
2169
2170        window_profiler.begin_draw();
2171        begin_input_at(&mut window_profiler, Instant::now());
2172        window_profiler.end_input(true);
2173        window_profiler.end_draw(None, 0);
2174
2175        let snapshot = window_profiler.input_latency_snapshot();
2176        assert!(snapshot.latency_histogram.is_empty());
2177        assert!(snapshot.events_per_frame_histogram.is_empty());
2178        assert_eq!(snapshot.mid_draw_events_dropped, 1);
2179    }
2180
2181    #[test]
2182    fn overlapping_trace_scopes_keep_tracing_enabled() {
2183        let _trace_test_guard = TraceTestGuard::new();
2184        let first_scope = trace_scope();
2185        let second_scope = trace_scope();
2186
2187        assert!(trace_enabled());
2188        drop(first_scope);
2189        assert!(trace_enabled());
2190        drop(second_scope);
2191        assert!(!trace_enabled());
2192    }
2193
2194    const FRAME: Duration = Duration::from_millis(16);
2195    static TRACE_TEST_LOCK: Mutex<()> = Mutex::new(());
2196
2197    struct TraceTestGuard {
2198        was_enabled: bool,
2199        _lock: MutexGuard<'static, ()>,
2200    }
2201
2202    impl TraceTestGuard {
2203        fn new() -> Self {
2204            let lock = TRACE_TEST_LOCK
2205                .lock()
2206                .unwrap_or_else(|poisoned| poisoned.into_inner());
2207            let was_enabled = trace_enabled();
2208            set_trace_enabled(false);
2209            Self {
2210                was_enabled,
2211                _lock: lock,
2212            }
2213        }
2214    }
2215
2216    impl Drop for TraceTestGuard {
2217        fn drop(&mut self) {
2218            set_trace_enabled(false);
2219            if self.was_enabled {
2220                set_trace_enabled(true);
2221            }
2222        }
2223    }
2224
2225    fn event_matches_window(event: FrameEvent, window_id: WindowId) -> bool {
2226        match event {
2227            FrameEvent::Draw(timing) => timing.window_id == window_id,
2228            FrameEvent::Present(timing) => timing.window_id == window_id,
2229        }
2230    }
2231
2232    fn begin_input_at(window_profiler: &mut WindowProfiler, started_at: Instant) {
2233        window_profiler
2234            .active_activities
2235            .push(WindowActivity::Input {
2236                started_at,
2237                kind: "test",
2238            });
2239    }
2240
2241    #[cfg(feature = "profiler")]
2242    fn draw_and_present(
2243        window_profiler: &mut WindowProfiler,
2244        presented_at: Instant,
2245        window_active: bool,
2246        next_frame_scheduled: bool,
2247    ) {
2248        record_test_draw(window_profiler, presented_at);
2249        window_profiler.record_present_at(
2250            presented_at,
2251            presented_at,
2252            window_active,
2253            next_frame_scheduled,
2254            false,
2255        );
2256    }
2257
2258    fn record_test_draw(window_profiler: &mut WindowProfiler, draw_end: Instant) {
2259        window_profiler.record_draw_timing(FrameTiming {
2260            window_id: window_profiler.window_id,
2261            dirty_at: Some(draw_end - Duration::from_millis(4)),
2262            invalidations: 1,
2263            draw_start: draw_end - Duration::from_millis(2),
2264            draw_end,
2265            refresh_interval: None,
2266            signal_at: None,
2267            phases: Default::default(),
2268        });
2269    }
2270}