Skip to main content

gpui_authoring/
profiler.rs

1#[cfg(feature = "profiler")]
2use hdrhistogram::Histogram;
3use itertools::Itertools;
4use scheduler::{Instant, SpawnTime};
5#[cfg(feature = "profiler")]
6use smallvec::SmallVec;
7use std::{
8    cell::LazyCell,
9    collections::{HashMap, VecDeque},
10    hash::{DefaultHasher, Hash, Hasher},
11    sync::{
12        Arc,
13        atomic::{AtomicU64, Ordering},
14    },
15    thread::ThreadId,
16    time::Duration,
17};
18
19mod actions;
20#[cfg(feature = "profiler")]
21pub mod hang;
22#[cfg(feature = "profiler")]
23pub mod journal;
24pub use actions::{ActionStatistics, ActionTiming, take_action_stats};
25
26use serde::{Deserialize, Serialize};
27
28#[cfg(feature = "profiler")]
29use crate::{Action, App, WindowId};
30use crate::{SharedString, TasksIncluded};
31
32#[cfg(feature = "profiler")]
33#[doc(hidden)]
34pub fn get_all_timings(included: gpui::TasksIncluded) -> Vec<gpui::ThreadTaskTimings> {
35    ThreadTaskTimings::collect(upgraded_thread_timings(), included)
36}
37
38#[cfg(feature = "profiler")]
39#[doc(hidden)]
40pub fn get_current_thread_timings(included: TasksIncluded) -> gpui::ThreadTaskTimings {
41    gpui::profiler::get_current_thread_task_timings(included)
42}
43
44#[cfg(feature = "profiler")]
45#[doc(hidden)]
46pub fn take_all_stats(included: TasksIncluded) -> Vec<gpui::ThreadTaskStatistics> {
47    ThreadTaskStatistics::collect_and_reset(upgraded_thread_timings(), included)
48}
49
50#[cfg(not(feature = "profiler"))]
51#[doc(hidden)]
52pub fn get_all_timings(_included: gpui::TasksIncluded) -> Vec<gpui::ThreadTaskTimings> {
53    Vec::new()
54}
55#[cfg(not(feature = "profiler"))]
56#[doc(hidden)]
57pub fn get_current_thread_timings(_included: TasksIncluded) -> gpui::ThreadTaskTimings {
58    gpui::ThreadTaskTimings {
59        thread_name: None,
60        thread_id: std::thread::current().id(),
61        timings: Vec::new(),
62        stats: TaskStatistics::default(),
63        total_pushed: 0,
64    }
65}
66#[cfg(not(feature = "profiler"))]
67#[doc(hidden)]
68pub fn take_all_stats(_included: TasksIncluded) -> Vec<gpui::ThreadTaskStatistics> {
69    Vec::new()
70}
71
72#[doc(hidden)]
73#[derive(Debug, Copy, Clone)]
74pub struct YieldTime(pub Instant);
75
76#[doc(hidden)]
77#[derive(Copy, Clone)]
78pub struct TaskTiming {
79    pub location: &'static core::panic::Location<'static>,
80    pub spawned: SpawnTime,
81    pub start: Instant,
82    pub end: YieldTime,
83}
84
85impl std::fmt::Debug for TaskTiming {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        f.debug_struct("TaskTiming")
88            .field("location", &self.location)
89            .field("since_spawned", &self.spawned.0.elapsed())
90            .field("last_poll_duration", &self.poll_duration())
91            .field("total_runtime", &self.since_spawn())
92            .finish()
93    }
94}
95
96#[doc(hidden)]
97#[derive(Debug, Copy, Clone)]
98pub struct ActiveTiming {
99    pub location: &'static core::panic::Location<'static>,
100    pub spawned: SpawnTime,
101    pub start: Instant,
102}
103
104impl TaskTiming {
105    /// A task timing with a duration of zero. Any task will replace this in history.
106    pub fn placeholder() -> Self {
107        let now = Instant::now();
108        Self {
109            location: std::panic::Location::caller(),
110            spawned: SpawnTime(now),
111            start: now,
112            end: YieldTime(now),
113        }
114    }
115
116    #[inline(always)]
117    pub fn poll_duration(&self) -> Duration {
118        self.end.0 - self.start
119    }
120
121    #[inline(always)]
122    fn since_spawn(&self) -> Duration {
123        self.end.0 - self.spawned.0
124    }
125}
126
127#[doc(hidden)]
128#[derive(Debug, Clone)]
129pub struct ThreadTaskTimings {
130    pub thread_name: Option<String>,
131    pub thread_id: ThreadId,
132    pub timings: Vec<TaskTiming>,
133    pub stats: TaskStatistics,
134    pub total_pushed: u64,
135}
136
137impl ThreadTaskTimings {
138    /// Convert upgraded per-thread timings into their structured format.
139    pub fn collect(
140        timings: Vec<(ThreadId, Arc<GuardedTaskTimings>)>,
141        included: TasksIncluded,
142    ) -> Vec<Self> {
143        timings
144            .into_iter()
145            .map(|(thread_id, timings)| {
146                let timings = timings.lock();
147                let thread_name = timings.thread_name.clone();
148                let total_pushed = timings.total_pushed;
149                let completed = &timings.timings;
150
151                let mut vec = Vec::with_capacity(completed.len() + 1); // +1 for running task
152                let (s1, s2) = completed.as_slices();
153                vec.extend_from_slice(s1);
154                vec.extend_from_slice(s2);
155                if let TasksIncluded::CompletedAndRunning = included
156                    && let Some(running) = timings.running
157                {
158                    vec.push(TaskTiming {
159                        location: running.location,
160                        spawned: running.spawned,
161                        start: running.start,
162                        end: YieldTime(Instant::now()),
163                    })
164                }
165
166                ThreadTaskTimings {
167                    thread_name,
168                    thread_id,
169                    timings: vec,
170                    stats: timings.stats.clone(),
171                    total_pushed,
172                }
173            })
174            .collect()
175    }
176}
177
178#[doc(hidden)]
179#[derive(Debug)]
180pub struct ThreadTaskStatistics {
181    pub thread_name: Option<String>,
182    pub thread_id: ThreadId,
183    pub stats: TaskStatistics,
184}
185
186impl ThreadTaskStatistics {
187    pub fn collect_and_reset(
188        timings: Vec<(ThreadId, Arc<GuardedTaskTimings>)>,
189        include_running: TasksIncluded,
190    ) -> Vec<Self> {
191        timings
192            .into_iter()
193            .map(|(thread_id, timings)| {
194                let mut timings = timings.lock();
195                let thread_name = timings.thread_name.clone();
196
197                let mut stats = std::mem::take(&mut timings.stats);
198                if let TasksIncluded::CompletedAndRunning = include_running
199                    && let Some(ActiveTiming {
200                        location,
201                        spawned,
202                        start,
203                    }) = timings.running
204                {
205                    let end = YieldTime(Instant::now());
206                    let timing = TaskTiming {
207                        location,
208                        spawned,
209                        start,
210                        end,
211                    };
212                    stats.add_runtime(timing);
213                    stats.add_yield_timing(timing);
214                }
215
216                Self {
217                    thread_name,
218                    thread_id,
219                    stats,
220                }
221            })
222            .collect()
223    }
224}
225
226/// Serializable variant of [`core::panic::Location`]
227#[derive(Debug, Clone, Serialize, Deserialize)]
228pub struct SerializedLocation {
229    /// Name of the source file
230    pub file: SharedString,
231    /// Line in the source file
232    pub line: u32,
233    /// Column in the source file
234    pub column: u32,
235}
236
237impl From<&core::panic::Location<'static>> for SerializedLocation {
238    fn from(value: &core::panic::Location<'static>) -> Self {
239        SerializedLocation {
240            file: value.file().into(),
241            line: value.line(),
242            column: value.column(),
243        }
244    }
245}
246
247/// Serializable variant of [`TaskTiming`]
248#[derive(Debug, Clone, Serialize, Deserialize)]
249pub struct SerializedTaskTiming {
250    /// Location of the timing
251    pub location: SerializedLocation,
252    /// Time at which the measurement was reported in nanoseconds
253    pub start: u128,
254    /// Duration of the measurement in nanoseconds
255    pub duration: u128,
256}
257
258impl SerializedTaskTiming {
259    /// Convert an array of [`TaskTiming`] into their serializable format
260    ///
261    /// # Params
262    ///
263    /// `anchor` - [`Instant`] that should be earlier than all timings to use as base anchor
264    pub fn convert(anchor: Instant, timings: &[TaskTiming]) -> Vec<SerializedTaskTiming> {
265        let serialized = timings
266            .iter()
267            .map(|timing| {
268                let start = timing.start.duration_since(anchor).as_nanos();
269                let duration = timing.end.0.duration_since(timing.start).as_nanos();
270                SerializedTaskTiming {
271                    location: timing.location.into(),
272                    start,
273                    duration,
274                }
275            })
276            .collect::<Vec<_>>();
277
278        serialized
279    }
280
281    /// `anchor` - [`Instant`] that should be earlier than all timings to use as base anchor
282    pub fn from(anchor: Instant, timing: TaskTiming) -> SerializedTaskTiming {
283        let start = timing.start.duration_since(anchor).as_nanos();
284        let duration = timing.end.0.duration_since(timing.start).as_nanos();
285        SerializedTaskTiming {
286            location: timing.location.into(),
287            start,
288            duration,
289        }
290    }
291}
292
293/// Serializable variant of [`ThreadTaskTimings`]
294#[derive(Debug, Clone, Serialize, Deserialize)]
295pub struct SerializedThreadTaskTimings {
296    /// Thread name
297    pub thread_name: Option<String>,
298    /// Hash of the thread id
299    pub thread_id: u64,
300    /// Timing records for this thread
301    pub timings: Vec<SerializedTaskTiming>,
302}
303
304impl SerializedThreadTaskTimings {
305    /// Convert [`ThreadTaskTimings`] into their serializable format
306    ///
307    /// # Params
308    ///
309    /// `anchor` - [`Instant`] that should be earlier than all timings to use as base anchor
310    pub fn convert(anchor: Instant, timings: ThreadTaskTimings) -> SerializedThreadTaskTimings {
311        let serialized_timings = SerializedTaskTiming::convert(anchor, &timings.timings);
312
313        let mut hasher = DefaultHasher::new();
314        timings.thread_id.hash(&mut hasher);
315        let thread_id = hasher.finish();
316
317        SerializedThreadTaskTimings {
318            thread_name: timings.thread_name,
319            thread_id,
320            timings: serialized_timings,
321        }
322    }
323}
324
325#[doc(hidden)]
326#[derive(Debug, Clone)]
327pub struct ThreadTimingsDelta {
328    /// Hashed thread id
329    pub thread_id: u64,
330    /// Thread name, if known
331    pub thread_name: Option<String>,
332    /// New timings since the last call. If the circular buffer wrapped around
333    /// since the previous poll, some entries may have been lost.
334    pub new_timings: Vec<SerializedTaskTiming>,
335}
336
337/// Tracks which timing events have already been seen so that callers can request only unseen events.
338#[doc(hidden)]
339pub struct ProfilingCollector {
340    startup_time: Instant,
341    cursors: HashMap<ThreadId, u64>,
342}
343
344impl ProfilingCollector {
345    pub fn new(startup_time: Instant) -> Self {
346        Self {
347            startup_time,
348            cursors: HashMap::default(),
349        }
350    }
351
352    pub fn startup_time(&self) -> Instant {
353        self.startup_time
354    }
355
356    pub fn collect_unseen(
357        &mut self,
358        all_timings: Vec<ThreadTaskTimings>,
359    ) -> Vec<ThreadTimingsDelta> {
360        let mut deltas = Vec::with_capacity(all_timings.len());
361
362        for thread in all_timings {
363            let mut hasher = DefaultHasher::new();
364            thread.thread_id.hash(&mut hasher);
365            let hashed_id = hasher.finish();
366
367            let prev_cursor = self.cursors.get(&thread.thread_id).copied().unwrap_or(0);
368            let buffer_len = thread.timings.len() as u64;
369            let buffer_start = thread.total_pushed.saturating_sub(buffer_len);
370
371            let mut slice = if prev_cursor < buffer_start {
372                // Cursor fell behind the buffer — some entries were evicted.
373                // Return everything still in the buffer.
374                thread.timings.as_slice()
375            } else {
376                let skip = (prev_cursor - buffer_start) as usize;
377                &thread.timings[skip.min(thread.timings.len())..]
378            };
379
380            let cursor_advance = thread.total_pushed;
381            self.cursors.insert(thread.thread_id, cursor_advance);
382
383            if slice.is_empty() {
384                continue;
385            }
386
387            let new_timings = SerializedTaskTiming::convert(self.startup_time, slice);
388
389            deltas.push(ThreadTimingsDelta {
390                thread_id: hashed_id,
391                thread_name: thread.thread_name,
392                new_timings,
393            });
394        }
395
396        deltas
397    }
398
399    pub fn reset(&mut self) {
400        self.cursors.clear();
401    }
402}
403
404// Allow 16MiB of task timing entries.
405// VecDeque grows by doubling its capacity when full, so keep this a power of 2 to avoid wasting
406// memory.
407#[cfg(feature = "profiler")]
408const MAX_TASK_TIMINGS: usize = (16 * 1024 * 1024) / core::mem::size_of::<TaskTiming>();
409
410#[doc(hidden)]
411pub(crate) type TaskTimings = VecDeque<TaskTiming>;
412
413#[doc(hidden)]
414pub type GuardedTaskTimings = spin::Mutex<ThreadTimings>;
415
416#[doc(hidden)]
417pub struct GlobalThreadTimings {
418    pub thread_id: ThreadId,
419    pub timings: std::sync::Weak<GuardedTaskTimings>,
420}
421
422#[doc(hidden)]
423#[derive(Debug, Clone)]
424pub struct TaskStatistics {
425    pub poll_time_to_beat: Duration,
426    pub runtime_to_beat: Duration,
427    pub longest_poll_times: [TaskTiming; 5],
428    pub longest_runtimes: [TaskTiming; 5],
429}
430
431impl std::fmt::Display for TaskStatistics {
432    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
433        f.write_str("Tasks that blocked the longest before yielding\n")?;
434        for timing in self.longest_poll_times {
435            f.write_fmt(format_args!(
436                "{:<20} - {}:{}\n",
437                format!("{:?}", timing.poll_duration()),
438                timing.location.file(),
439                timing.location.column()
440            ))?;
441        }
442        f.write_str("Tasks that ran the longest\n")?;
443        for timing in self.longest_runtimes {
444            f.write_fmt(format_args!(
445                "{:<20} - {}:{}\n",
446                format!("{:?}", timing.since_spawn()),
447                timing.location.file(),
448                timing.location.column()
449            ))?;
450        }
451        Ok(())
452    }
453}
454
455impl Default for TaskStatistics {
456    fn default() -> Self {
457        Self {
458            // Do not track polls that are not problematic
459            // this keeps more calls on the fast path
460            poll_time_to_beat: Duration::from_micros(100),
461            runtime_to_beat: Duration::from_micros(100),
462            longest_poll_times: [TaskTiming::placeholder(); 5],
463            longest_runtimes: [TaskTiming::placeholder(); 5],
464        }
465    }
466}
467
468impl TaskStatistics {
469    #[inline(always)]
470    fn add_yield_timing(&mut self, task: TaskTiming) {
471        let yielded_after = task.poll_duration();
472        if yielded_after >= self.poll_time_to_beat {
473            std::hint::cold_path(); // most tasks are not the worst, optimize for that
474            let to_replace = self
475                .longest_poll_times
476                .iter()
477                .position_min_by_key(|task| task.since_spawn())
478                .expect("guarded by the comparison with nth_longest_yield_time");
479            self.longest_poll_times[to_replace] = task;
480
481            self.poll_time_to_beat = self
482                .longest_poll_times
483                .iter()
484                .map(|task| task.since_spawn())
485                .min()
486                .expect("never empty");
487        }
488    }
489
490    #[inline(always)]
491    fn add_runtime(&mut self, task: TaskTiming) {
492        let runtime = task.since_spawn();
493        if runtime >= self.runtime_to_beat {
494            std::hint::cold_path(); // most tasks are not the worst, optimize for that
495            let to_replace = self
496                .longest_runtimes
497                .iter()
498                .position_min_by_key(|task| task.since_spawn())
499                .expect("guarded by the comparison with nth_longest_yield_time");
500            self.longest_runtimes[to_replace] = task;
501
502            self.runtime_to_beat = self
503                .longest_runtimes
504                .iter()
505                .map(|task| task.since_spawn())
506                .min()
507                .expect("never empty");
508        }
509    }
510}
511
512#[doc(hidden)]
513pub static GLOBAL_THREAD_TIMINGS: spin::Mutex<Vec<GlobalThreadTimings>> =
514    spin::Mutex::new(Vec::new());
515
516/// Upgrades all live per-thread timing handles, holding the global registry
517/// lock only for the duration of the upgrades.
518///
519/// The upgraded `Arc`s must never be dropped while `GLOBAL_THREAD_TIMINGS` is
520/// locked: dropping the last strong reference runs [`ThreadTimings::drop`],
521/// which locks `GLOBAL_THREAD_TIMINGS` again and would deadlock the
522/// non-reentrant spinlock. A thread exiting concurrently can hand off its last
523/// reference to us at any time, so callers of this function process (lock,
524/// read, drop) the returned handles only after the global lock is released.
525fn upgraded_thread_timings() -> Vec<(ThreadId, Arc<GuardedTaskTimings>)> {
526    let global_thread_timings = GLOBAL_THREAD_TIMINGS.lock();
527    global_thread_timings
528        .iter()
529        .filter_map(|t| Some((t.thread_id, t.timings.upgrade()?)))
530        .collect()
531}
532
533thread_local! {
534    #[doc(hidden)]
535    pub static THREAD_TIMINGS: LazyCell<Arc<GuardedTaskTimings>> = LazyCell::new(|| {
536        let current_thread = std::thread::current();
537        let thread_name = current_thread.name();
538        let thread_id = current_thread.id();
539        let timings = ThreadTimings::new(thread_name.map(|e| e.to_string()), thread_id);
540        let timings = Arc::new(spin::Mutex::new(timings));
541
542        {
543            let timings = Arc::downgrade(&timings);
544            let global_timings = GlobalThreadTimings {
545                thread_id: std::thread::current().id(),
546                timings,
547            };
548            GLOBAL_THREAD_TIMINGS.lock().push(global_timings);
549        }
550
551        timings
552    });
553}
554
555#[doc(hidden)]
556pub struct ThreadTimings {
557    pub thread_name: Option<String>,
558    pub thread_id: ThreadId,
559    pub timings: TaskTimings,
560    pub running: Option<ActiveTiming>,
561    pub stats: TaskStatistics,
562    pub total_pushed: u64,
563}
564
565impl ThreadTimings {
566    pub fn new(thread_name: Option<String>, thread_id: ThreadId) -> Self {
567        ThreadTimings {
568            thread_name,
569            thread_id,
570            timings: TaskTimings::new(),
571            stats: TaskStatistics::default(),
572            total_pushed: 0,
573            running: None,
574        }
575    }
576
577    #[cfg(feature = "profiler")]
578    pub fn update_running_task(
579        &mut self,
580        spawned: SpawnTime,
581        location: &'static std::panic::Location<'_>,
582    ) {
583        let start = Instant::now();
584        self.running = Some(ActiveTiming {
585            spawned,
586            location,
587            start,
588        });
589    }
590    #[cfg(not(feature = "profiler"))]
591    pub fn update_running_task(&mut self, _: SpawnTime, _: &'static std::panic::Location<'_>) {}
592
593    #[cfg(feature = "profiler")]
594    pub fn save_task_timing(&mut self, ended: YieldTime) -> TaskTiming {
595        let ActiveTiming {
596            location,
597            start,
598            spawned,
599        } = self
600            .running
601            .take()
602            .expect("this function is only ever called after register_task_start");
603
604        let timing = TaskTiming {
605            location,
606            spawned,
607            start,
608            end: ended,
609        };
610        self.stats.add_yield_timing(timing);
611        self.stats.add_runtime(timing);
612
613        if trace_enabled() {
614            std::hint::cold_path(); // optimize for when the profiling is off
615            if self.timings.len() >= MAX_TASK_TIMINGS {
616                self.timings.pop_front();
617            }
618            self.timings.push_back(timing);
619            self.total_pushed += 1;
620        }
621        timing
622    }
623    #[cfg(not(feature = "profiler"))]
624    pub fn save_task_timing(&mut self, _: YieldTime) {}
625
626    // Running tasks are included in the reliability trace, which is written
627    // whenever the foreground executor makes no progress for > n seconds
628    pub fn get_thread_task_timings(&self, includes: TasksIncluded) -> ThreadTaskTimings {
629        ThreadTaskTimings {
630            thread_name: self.thread_name.clone(),
631            thread_id: self.thread_id,
632            timings: self
633                .timings
634                .iter()
635                .cloned()
636                .chain(
637                    self.running
638                        .filter(|_| matches!(includes, TasksIncluded::CompletedAndRunning))
639                        .map(|running| TaskTiming {
640                            spawned: running.spawned,
641                            location: running.location,
642                            start: running.start,
643                            end: YieldTime(Instant::now()),
644                        }),
645                )
646                .collect(),
647            stats: self.stats.clone(),
648            total_pushed: self.total_pushed,
649        }
650    }
651}
652
653impl Drop for ThreadTimings {
654    fn drop(&mut self) {
655        let mut thread_timings = GLOBAL_THREAD_TIMINGS.lock();
656
657        let Some((index, _)) = thread_timings
658            .iter()
659            .enumerate()
660            .find(|(_, t)| t.thread_id == self.thread_id)
661        else {
662            return;
663        };
664        thread_timings.swap_remove(index);
665    }
666}
667
668#[doc(hidden)]
669pub fn update_running_task(spawned: SpawnTime, location: &'static std::panic::Location<'_>) {
670    #[cfg(feature = "profiler")]
671    journal::begin_foreground_turn();
672    THREAD_TIMINGS.with(|timings| {
673        timings.lock().update_running_task(spawned, location);
674    });
675}
676
677#[doc(hidden)]
678pub fn save_task_timing() {
679    let yielded_at = YieldTime(Instant::now());
680    #[cfg(feature = "profiler")]
681    {
682        let timing = THREAD_TIMINGS.with(|timings| timings.lock().save_task_timing(yielded_at));
683        journal::record_task_poll(timing);
684    }
685    #[cfg(not(feature = "profiler"))]
686    THREAD_TIMINGS.with(|timings| {
687        timings.lock().save_task_timing(yielded_at);
688    });
689}
690
691/// Installs gpui's task profiler into the platform hook point.
692///
693/// Platform backends report runnable polling through
694/// [`gpui_platform::profiler::update_running_task`] and
695/// [`gpui_platform::profiler::save_task_timing`]; this wires those calls to
696/// the timing machinery in this module. Repeated calls are ignored.
697pub fn install_profiler_hooks() {
698    gpui_platform::profiler::set_task_profiler(update_running_task, save_task_timing);
699}
700
701#[doc(hidden)]
702pub fn get_current_thread_task_timings(include_running: TasksIncluded) -> ThreadTaskTimings {
703    THREAD_TIMINGS.with(|timings| timings.lock().get_thread_task_timings(include_running))
704}
705
706const TRACE_SETTING_ENABLED: u64 = 1 << 63;
707const TRACE_SCOPE_COUNT_MASK: u64 = TRACE_SETTING_ENABLED - 1;
708static TRACE_STATE: AtomicU64 = AtomicU64::new(0);
709
710/// Enables or disables profiler trace collection at runtime.
711///
712/// When transitioning from enabled to disabled, `add_task_timing` becomes
713/// cheaper since only cheap statistics are gathered. The existing per-thread
714/// task buffers and the frame-event buffer are cleared so stale data isn't
715/// reported after a later re-enable. Active trace scopes keep collection enabled
716/// until the last scope ends. Calls with the current setting are a no-op.
717pub fn set_trace_enabled(enabled: bool) -> bool {
718    let mut state = TRACE_STATE.load(Ordering::Acquire);
719    loop {
720        let was_enabled = state & TRACE_SETTING_ENABLED != 0;
721        if was_enabled == enabled {
722            return false;
723        }
724
725        let next_state = if enabled {
726            state | TRACE_SETTING_ENABLED
727        } else {
728            state & TRACE_SCOPE_COUNT_MASK
729        };
730        match TRACE_STATE.compare_exchange_weak(
731            state,
732            next_state,
733            Ordering::AcqRel,
734            Ordering::Acquire,
735        ) {
736            Ok(_) => {
737                if next_state == 0 {
738                    clear_trace_buffers();
739                }
740                return true;
741            }
742            Err(updated_state) => state = updated_state,
743        }
744    }
745}
746
747#[cfg(any(feature = "bench-support", all(test, feature = "profiler")))]
748pub(crate) struct TraceGuard;
749
750#[cfg(any(feature = "bench-support", all(test, feature = "profiler")))]
751pub(crate) fn trace_scope() -> TraceGuard {
752    let incremented = TRACE_STATE.fetch_update(Ordering::AcqRel, Ordering::Acquire, |state| {
753        (state & TRACE_SCOPE_COUNT_MASK < TRACE_SCOPE_COUNT_MASK).then_some(state + 1)
754    });
755    assert!(incremented.is_ok(), "too many active profiler trace scopes");
756    TraceGuard
757}
758
759#[cfg(any(feature = "bench-support", all(test, feature = "profiler")))]
760impl Drop for TraceGuard {
761    fn drop(&mut self) {
762        let previous_state =
763            TRACE_STATE.fetch_update(Ordering::AcqRel, Ordering::Acquire, |state| {
764                (state & TRACE_SCOPE_COUNT_MASK > 0).then_some(state - 1)
765            });
766        match previous_state {
767            Ok(1) => clear_trace_buffers(),
768            Ok(_) => {}
769            Err(_) => debug_assert!(false, "profiler trace scope count underflowed"),
770        }
771    }
772}
773
774/// Returns whether profiler trace collection is enabled.
775pub fn trace_enabled() -> bool {
776    TRACE_STATE.load(Ordering::Relaxed) != 0
777}
778
779fn clear_trace_buffers() {
780    for (_, timings) in upgraded_thread_timings() {
781        let mut timings = timings.lock();
782        timings.timings.clear();
783        timings.timings.shrink_to_fit();
784        timings.total_pushed = 0;
785    }
786    #[cfg(feature = "profiler")]
787    {
788        let mut frames = FRAME_TIMINGS.lock();
789        frames.timings.clear();
790        frames.timings.shrink_to_fit();
791        frames.total_pushed = 0;
792    }
793}
794
795/// Timing for a single drawn window frame.
796#[cfg(feature = "profiler")]
797#[derive(Debug, Copy, Clone)]
798pub struct FrameTiming {
799    /// The window that was drawn.
800    pub window_id: WindowId,
801    /// When the frame first became dirty (its first invalidation). `None` if
802    /// profiler tracing was not yet enabled when the invalidation occurred.
803    pub dirty_at: Option<Instant>,
804    /// Number of invalidations coalesced into this frame.
805    pub invalidations: u64,
806    /// When `Window::draw` started.
807    pub draw_start: Instant,
808    /// When `Window::draw` finished.
809    pub draw_end: Instant,
810}
811
812#[cfg(feature = "profiler")]
813impl FrameTiming {
814    /// Time spent inside `Window::draw`.
815    pub fn draw_duration(&self) -> Duration {
816        self.draw_end.duration_since(self.draw_start)
817    }
818
819    /// Time from the frame's first invalidation to the end of its draw, if the
820    /// first invalidation was observed.
821    pub fn dirty_to_draw_duration(&self) -> Option<Duration> {
822        self.dirty_at
823            .map(|dirty_at| self.draw_end.duration_since(dirty_at))
824    }
825}
826
827/// Work spent submitting a window frame to the platform.
828#[cfg(feature = "profiler")]
829#[derive(Debug, Copy, Clone)]
830pub struct PresentTiming {
831    /// The window whose frame was submitted.
832    pub window_id: WindowId,
833    /// When the platform submission began.
834    pub present_start: Instant,
835    /// When the platform submission completed.
836    pub present_end: Instant,
837    /// The interval since the previous newly drawn frame was submitted, when
838    /// both frames belong to an active animation.
839    pub animation_interval: Option<Duration>,
840}
841
842#[cfg(feature = "profiler")]
843impl PresentTiming {
844    /// Time spent submitting the frame to the platform.
845    pub fn present_duration(&self) -> Duration {
846        self.present_end.duration_since(self.present_start)
847    }
848}
849
850/// A frame event observed by the profiler.
851#[cfg(feature = "profiler")]
852#[derive(Debug, Copy, Clone)]
853pub enum FrameEvent {
854    /// A window frame was drawn.
855    Draw(FrameTiming),
856    /// A newly drawn window frame was presented.
857    Present(PresentTiming),
858}
859
860/// A point-in-time snapshot of the frame-duration histograms for a window,
861/// suitable for external formatting.
862#[cfg(feature = "profiler")]
863#[derive(Clone)]
864pub struct FrameDurationSnapshot {
865    /// Histogram of durations from the first invalidation through presentation, in nanoseconds.
866    pub dirty_to_present_histogram: Histogram<u64>,
867    /// Histogram of `Window::draw` durations, in nanoseconds.
868    pub draw_duration_histogram: Histogram<u64>,
869    /// Histogram of intervals between consecutively presented frames while the
870    /// window was animating, in nanoseconds.
871    pub present_interval_histogram: Histogram<u64>,
872}
873
874/// A point-in-time snapshot of the input-latency histograms for a window,
875/// suitable for external formatting.
876#[cfg(feature = "profiler")]
877#[derive(Clone)]
878pub struct InputLatencySnapshot {
879    /// Histogram of input-to-frame latency samples, in nanoseconds.
880    pub latency_histogram: Histogram<u64>,
881    /// Histogram of input events coalesced per rendered frame.
882    pub events_per_frame_histogram: Histogram<u64>,
883    /// Count of input events that arrived mid-draw and were excluded from
884    /// latency recording.
885    pub mid_draw_events_dropped: u64,
886}
887
888#[cfg(feature = "profiler")]
889enum WindowActivity {
890    Input {
891        started_at: Instant,
892        kind: &'static str,
893    },
894    Draw {
895        started_at: Instant,
896    },
897}
898
899/// Collects profiling information for one window.
900///
901/// Aggregate histograms are always populated when the `profiler` feature is
902/// compiled in. Individual draw and present events are added to the global
903/// profiler buffer only while tracing is enabled.
904#[cfg(feature = "profiler")]
905pub struct WindowProfiler {
906    window_id: WindowId,
907    active_activities: SmallVec<[WindowActivity; 4]>,
908    active_actions: SmallVec<[(&'static str, Instant); 2]>,
909    dirty_to_present_histogram: Histogram<u64>,
910    draw_duration_histogram: Histogram<u64>,
911    present_interval_histogram: Histogram<u64>,
912    first_input_at: Option<Instant>,
913    pending_input_count: u64,
914    input_latency_histogram: Histogram<u64>,
915    events_per_frame_histogram: Histogram<u64>,
916    mid_draw_events_dropped: u64,
917    last_present_at: Option<Instant>,
918    animating_at_last_present: bool,
919    pending_frame: Option<FrameTiming>,
920}
921
922#[cfg(feature = "profiler")]
923impl WindowProfiler {
924    /// Creates a profiler for a window.
925    pub fn new(window_id: WindowId) -> anyhow::Result<Self> {
926        let profiler = Self {
927            window_id,
928            active_activities: SmallVec::new(),
929            active_actions: SmallVec::new(),
930            dirty_to_present_histogram: Histogram::new(3).map_err(|error| {
931                anyhow::anyhow!("Failed to create dirty-to-present histogram: {error}")
932            })?,
933            draw_duration_histogram: Histogram::new(3).map_err(|error| {
934                anyhow::anyhow!("Failed to create draw duration histogram: {error}")
935            })?,
936            present_interval_histogram: Histogram::new(3).map_err(|error| {
937                anyhow::anyhow!("Failed to create present interval histogram: {error}")
938            })?,
939            first_input_at: None,
940            pending_input_count: 0,
941            input_latency_histogram: Histogram::new(3).map_err(|error| {
942                anyhow::anyhow!("Failed to create input latency histogram: {error}")
943            })?,
944            events_per_frame_histogram: Histogram::new(3).map_err(|error| {
945                anyhow::anyhow!("Failed to create events per frame histogram: {error}")
946            })?,
947            mid_draw_events_dropped: 0,
948            last_present_at: None,
949            animating_at_last_present: false,
950            pending_frame: None,
951        };
952        journal::record_frame_pending(window_id, Instant::now());
953        Ok(profiler)
954    }
955
956    /// Records the beginning of an input dispatch. `kind` names the platform
957    /// input variant being dispatched (see [`crate::PlatformInput::kind_name`]).
958    pub fn begin_input(&mut self, kind: &'static str) {
959        journal::begin_foreground_turn();
960        self.active_activities.push(WindowActivity::Input {
961            started_at: Instant::now(),
962            kind,
963        });
964    }
965
966    /// Records the end of an input dispatch.
967    pub fn end_input(&mut self, caused_invalidation: bool) {
968        let Some(WindowActivity::Input { started_at, kind }) = self.active_activities.pop() else {
969            debug_assert!(false, "input activity must be the current window activity");
970            journal::end_foreground_turn();
971            return;
972        };
973
974        if !journal::power_interrupted_since(started_at) {
975            journal::record_input(journal::InputTiming {
976                kind,
977                start: started_at,
978                end: Instant::now(),
979                caused_invalidation,
980            });
981        }
982        journal::end_foreground_turn();
983
984        if !caused_invalidation || !journal::frame_sample_is_valid(self.window_id, started_at) {
985            return;
986        }
987        if self
988            .first_input_at
989            .is_some_and(|at| !journal::frame_sample_is_valid(self.window_id, at))
990        {
991            self.first_input_at = None;
992            self.pending_input_count = 0;
993        }
994
995        let arrived_during_draw = self
996            .active_activities
997            .iter()
998            .any(|activity| matches!(activity, WindowActivity::Draw { .. }));
999        if arrived_during_draw {
1000            self.mid_draw_events_dropped += 1;
1001        } else {
1002            self.first_input_at.get_or_insert(started_at);
1003            self.pending_input_count += 1;
1004        }
1005    }
1006
1007    /// Records the beginning of an action handler.
1008    pub fn begin_action_handler(&mut self, action: &(dyn Action + 'static), cx: &mut App) {
1009        journal::begin_foreground_turn();
1010        let name = actions::update_running_action(action, cx);
1011        self.active_actions.push((name, Instant::now()));
1012    }
1013
1014    /// Records the end of the current action handler.
1015    pub fn end_action_handler(&mut self) {
1016        // Dual-write to the legacy aggregate store; its single global running
1017        // slot misbehaves when tests run actions concurrently, which is why
1018        // the journal entry is tracked here on the window instead.
1019        actions::save_action_timing();
1020        let Some((name, start)) = self.active_actions.pop() else {
1021            debug_assert!(false, "action handler must be begun before it ends");
1022            journal::end_foreground_turn();
1023            return;
1024        };
1025        if !journal::power_interrupted_since(start) {
1026            journal::record_action(ActionTiming {
1027                name,
1028                start,
1029                end: Instant::now(),
1030            });
1031        }
1032        journal::end_foreground_turn();
1033    }
1034
1035    /// Records the beginning of a window draw.
1036    pub fn begin_draw(&mut self) {
1037        journal::begin_foreground_turn();
1038        let started_at = Instant::now();
1039        journal::record_frame_pending(self.window_id, started_at);
1040        self.active_activities
1041            .push(WindowActivity::Draw { started_at });
1042    }
1043
1044    /// Records the end of a window draw and returns the draw duration.
1045    pub fn end_draw(&mut self, dirty_at: Option<Instant>, invalidations: u64) -> Duration {
1046        let Some(WindowActivity::Draw {
1047            started_at: draw_start,
1048        }) = self.active_activities.pop()
1049        else {
1050            debug_assert!(false, "draw activity must be the current window activity");
1051            journal::end_foreground_turn();
1052            return Duration::ZERO;
1053        };
1054
1055        let draw_end = Instant::now();
1056        let frame_timing = FrameTiming {
1057            window_id: self.window_id,
1058            dirty_at: dirty_at.filter(|at| journal::frame_sample_is_valid(self.window_id, *at)),
1059            invalidations,
1060            draw_start,
1061            draw_end,
1062        };
1063        let draw_duration = frame_timing.draw_duration();
1064        if !journal::power_interrupted_since(draw_start) {
1065            self.record_draw_timing(frame_timing);
1066        }
1067        journal::end_foreground_turn();
1068        draw_duration
1069    }
1070
1071    /// Records that a frame was presented.
1072    ///
1073    /// `next_frame_scheduled` marks the animation state for the interval ending
1074    /// at the next newly drawn frame's presentation.
1075    pub fn record_present(
1076        &mut self,
1077        present_start: Instant,
1078        present_end: Instant,
1079        window_active: bool,
1080        next_frame_scheduled: bool,
1081    ) {
1082        self.record_present_at(
1083            present_start,
1084            present_end,
1085            window_active,
1086            next_frame_scheduled,
1087        );
1088    }
1089
1090    /// Returns a snapshot of the current input-latency histograms.
1091    pub fn input_latency_snapshot(&self) -> InputLatencySnapshot {
1092        InputLatencySnapshot {
1093            latency_histogram: self.input_latency_histogram.clone(),
1094            events_per_frame_histogram: self.events_per_frame_histogram.clone(),
1095            mid_draw_events_dropped: self.mid_draw_events_dropped,
1096        }
1097    }
1098
1099    /// Returns a snapshot of the current frame-duration histograms.
1100    pub fn frame_duration_snapshot(&self) -> FrameDurationSnapshot {
1101        FrameDurationSnapshot {
1102            dirty_to_present_histogram: self.dirty_to_present_histogram.clone(),
1103            draw_duration_histogram: self.draw_duration_histogram.clone(),
1104            present_interval_histogram: self.present_interval_histogram.clone(),
1105        }
1106    }
1107
1108    fn record_present_at(
1109        &mut self,
1110        present_start: Instant,
1111        present_end: Instant,
1112        window_active: bool,
1113        next_frame_scheduled: bool,
1114    ) {
1115        if let Some(first_input_at) = self.first_input_at.take()
1116            && journal::frame_sample_is_valid(self.window_id, first_input_at)
1117        {
1118            let latency_nanos = present_end.duration_since(first_input_at).as_nanos() as u64;
1119            self.input_latency_histogram.record(latency_nanos).ok();
1120            if self.pending_input_count > 0 {
1121                self.events_per_frame_histogram
1122                    .record(self.pending_input_count)
1123                    .ok();
1124            }
1125        }
1126        self.pending_input_count = 0;
1127
1128        let frame = self
1129            .pending_frame
1130            .take()
1131            .filter(|frame| journal::frame_sample_is_valid(self.window_id, frame.draw_start))
1132            .map(|mut frame| {
1133                frame.dirty_at = frame
1134                    .dirty_at
1135                    .filter(|at| journal::frame_sample_is_valid(self.window_id, *at));
1136                frame
1137            });
1138        let animation_interval =
1139            if frame.is_some() && self.animating_at_last_present && window_active {
1140                self.last_present_at
1141                    .filter(|at| journal::frame_sample_is_valid(self.window_id, *at))
1142                    .map(|last_present_at| present_end.duration_since(last_present_at))
1143            } else {
1144                None
1145            };
1146        let present_timing = PresentTiming {
1147            window_id: self.window_id,
1148            present_start,
1149            present_end,
1150            animation_interval,
1151        };
1152        journal::record_present(present_timing, frame);
1153
1154        let Some(frame) = frame else {
1155            return;
1156        };
1157
1158        if let Some(dirty_at) = frame.dirty_at
1159            && let Err(error) = self
1160                .dirty_to_present_histogram
1161                .record(present_end.duration_since(dirty_at).as_nanos() as u64)
1162        {
1163            log::error!("failed to record dirty-to-present frame timing: {error}");
1164        }
1165
1166        if let Some(animation_interval) = animation_interval {
1167            self.present_interval_histogram
1168                .record(animation_interval.as_nanos() as u64)
1169                .ok();
1170        }
1171        record_frame_event(FrameEvent::Present(present_timing));
1172
1173        self.last_present_at = Some(present_end);
1174        self.animating_at_last_present = next_frame_scheduled && window_active;
1175    }
1176
1177    fn record_draw_timing(&mut self, timing: FrameTiming) {
1178        self.record_draw_duration(timing.draw_duration());
1179        self.pending_frame = Some(timing);
1180        record_frame_event(FrameEvent::Draw(timing));
1181        journal::record_draw(timing);
1182    }
1183
1184    fn record_draw_duration(&mut self, duration: Duration) {
1185        self.draw_duration_histogram
1186            .record(duration.as_nanos() as u64)
1187            .ok();
1188    }
1189}
1190
1191#[cfg(feature = "profiler")]
1192impl Drop for WindowProfiler {
1193    fn drop(&mut self) {
1194        journal::record_window_closed(self.window_id);
1195    }
1196}
1197
1198// Allow 16MiB of frame event entries.
1199#[cfg(feature = "profiler")]
1200const MAX_FRAME_TIMINGS: usize = (16 * 1024 * 1024) / core::mem::size_of::<FrameEvent>();
1201
1202#[cfg(feature = "profiler")]
1203struct FrameTimings {
1204    timings: VecDeque<FrameEvent>,
1205    total_pushed: u64,
1206}
1207
1208#[cfg(feature = "profiler")]
1209static FRAME_TIMINGS: spin::Mutex<FrameTimings> = spin::Mutex::new(FrameTimings {
1210    timings: VecDeque::new(),
1211    total_pushed: 0,
1212});
1213
1214/// Records a frame event.
1215///
1216/// No-op unless profiler tracing is enabled via [`set_trace_enabled`].
1217#[cfg(feature = "profiler")]
1218pub fn record_frame_event(event: FrameEvent) {
1219    if !trace_enabled() {
1220        return;
1221    }
1222    std::hint::cold_path(); // optimize for when profiling is off
1223
1224    let mut frames = FRAME_TIMINGS.lock();
1225    if frames.timings.len() >= MAX_FRAME_TIMINGS {
1226        frames.timings.pop_front();
1227    }
1228    frames.timings.push_back(event);
1229    frames.total_pushed += 1;
1230}
1231
1232/// Drains frame events recorded after this collector was created, tracking a
1233/// cursor so each call to [`Self::collect_unseen`] returns only new entries.
1234#[cfg(feature = "profiler")]
1235pub struct FrameTimingCollector {
1236    cursor: u64,
1237}
1238
1239#[cfg(feature = "profiler")]
1240impl Default for FrameTimingCollector {
1241    fn default() -> Self {
1242        Self::new()
1243    }
1244}
1245
1246#[cfg(feature = "profiler")]
1247impl FrameTimingCollector {
1248    /// Creates a collector that only sees frame events recorded from this point on.
1249    pub fn new() -> Self {
1250        Self {
1251            cursor: FRAME_TIMINGS.lock().total_pushed,
1252        }
1253    }
1254
1255    /// Returns frame events recorded since the previous call (or since the
1256    /// collector was created). If the ring buffer wrapped around since the
1257    /// previous poll, the evicted entries are lost.
1258    pub fn collect_unseen(&mut self) -> Vec<FrameEvent> {
1259        let frames = FRAME_TIMINGS.lock();
1260        let buffer_len = frames.timings.len() as u64;
1261        let buffer_start = frames.total_pushed.saturating_sub(buffer_len);
1262        let skip = self.cursor.saturating_sub(buffer_start) as usize;
1263        let unseen = frames
1264            .timings
1265            .iter()
1266            .skip(skip.min(frames.timings.len()))
1267            .copied()
1268            .collect();
1269        self.cursor = frames.total_pushed;
1270        unseen
1271    }
1272}
1273
1274/// Serializes the tests that observe or change the process-global trace state.
1275///
1276/// `trace_scope` is global by design: holding one reports tracing as enabled on
1277/// every thread, so a test that asserts on `trace_enabled()` or on the frame
1278/// event buffer has to be the only scope holder. The `app::bench_context` tests
1279/// that run a `TraceScope` take this lock too.
1280#[cfg(all(test, any(feature = "profiler", feature = "bench-support")))]
1281pub(crate) fn trace_test_lock() -> std::sync::MutexGuard<'static, ()> {
1282    static TRACE_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1283    TRACE_TEST_LOCK
1284        .lock()
1285        .unwrap_or_else(|poisoned| poisoned.into_inner())
1286}
1287
1288#[cfg(all(test, feature = "profiler"))]
1289mod tests {
1290    use super::*;
1291    use std::sync::MutexGuard;
1292
1293    #[test]
1294    fn interruptions_drop_latency_samples_but_hiding_keeps_draw_work() {
1295        for sleep in [false, true] {
1296            let (_journal, _guard) = journal::install_test_foreground_journal(64, 4);
1297            let id = WindowId::from(1);
1298            let mut profiler = WindowProfiler::new(id).expect("valid histograms");
1299            let old = Instant::now() - Duration::from_secs(1);
1300            record_test_draw(&mut profiler, old);
1301            profiler.record_present_at(old, old, true, true);
1302            profiler.first_input_at = Some(old);
1303            profiler.pending_input_count = 1;
1304            profiler.begin_draw();
1305            if sleep {
1306                journal::record_power_transition(journal::PowerState::Suspended);
1307                journal::record_power_transition(journal::PowerState::Awake);
1308            } else {
1309                journal::record_window_visibility(id, crate::WindowVisibility::Hidden);
1310                journal::record_window_visibility(id, crate::WindowVisibility::Visible);
1311            }
1312            profiler.end_draw(Some(old), 1);
1313            let now = Instant::now();
1314            profiler.record_present_at(now, now, true, true);
1315            assert_eq!(
1316                profiler.draw_duration_histogram.len(),
1317                if sleep { 1 } else { 2 }
1318            );
1319            assert_eq!(profiler.input_latency_histogram.len(), 0);
1320            assert_eq!(profiler.dirty_to_present_histogram.len(), 1);
1321            assert_eq!(profiler.present_interval_histogram.len(), 0);
1322            profiler.begin_draw();
1323            profiler.end_draw(Some(Instant::now()), 1);
1324            let now = Instant::now();
1325            profiler.record_present_at(now, now, true, true);
1326            assert_eq!(profiler.dirty_to_present_histogram.len(), 2);
1327        }
1328    }
1329
1330    #[test]
1331    fn records_draw_events_only_while_tracing() {
1332        let _trace_test_guard = TraceTestGuard::new();
1333        let window_id = WindowId::from(0xD0A0);
1334        let mut window_profiler =
1335            WindowProfiler::new(window_id).expect("window profiler should initialize");
1336        let dirty_at = Instant::now();
1337        let mut collector = FrameTimingCollector::new();
1338
1339        window_profiler.begin_draw();
1340        window_profiler.end_draw(Some(dirty_at), 3);
1341        assert!(
1342            collector
1343                .collect_unseen()
1344                .iter()
1345                .all(|event| !event_matches_window(*event, window_id))
1346        );
1347
1348        set_trace_enabled(true);
1349        let mut collector = FrameTimingCollector::new();
1350        window_profiler.begin_draw();
1351        window_profiler.end_draw(Some(dirty_at), 3);
1352
1353        let timing = collector
1354            .collect_unseen()
1355            .into_iter()
1356            .find_map(|event| match event {
1357                FrameEvent::Draw(timing) if timing.window_id == window_id => Some(timing),
1358                _ => None,
1359            })
1360            .expect("draw event should be recorded while tracing");
1361        assert_eq!(timing.dirty_at, Some(dirty_at));
1362        assert_eq!(timing.invalidations, 3);
1363        assert!(timing.draw_start >= dirty_at);
1364    }
1365
1366    #[test]
1367    fn records_present_events_for_newly_drawn_frames() {
1368        let _trace_test_guard = TraceTestGuard::new();
1369        set_trace_enabled(true);
1370        let window_id = WindowId::from(0xA11E);
1371        let mut window_profiler =
1372            WindowProfiler::new(window_id).expect("window profiler should initialize");
1373        let start = Instant::now();
1374        let mut collector = FrameTimingCollector::new();
1375
1376        record_test_draw(&mut window_profiler, start);
1377        window_profiler.record_present_at(start, start, true, true);
1378        record_test_draw(&mut window_profiler, start + FRAME);
1379        window_profiler.record_present_at(start + FRAME, start + FRAME, true, true);
1380        window_profiler.record_present_at(
1381            start + FRAME + FRAME / 2,
1382            start + FRAME + FRAME / 2,
1383            true,
1384            true,
1385        );
1386
1387        let present_timings = collector
1388            .collect_unseen()
1389            .into_iter()
1390            .filter_map(|event| match event {
1391                FrameEvent::Present(timing) if timing.window_id == window_id => Some(timing),
1392                _ => None,
1393            })
1394            .collect::<Vec<_>>();
1395        let [first_present, second_present] = present_timings.as_slice() else {
1396            panic!("expected exactly two present events, got {present_timings:?}");
1397        };
1398        assert_eq!(first_present.animation_interval, None);
1399        assert_eq!(second_present.animation_interval, Some(FRAME));
1400
1401        #[cfg(feature = "profiler")]
1402        {
1403            assert_eq!(window_profiler.present_interval_histogram.len(), 1);
1404            assert!(
1405                window_profiler.present_interval_histogram.max()
1406                    >= second_present
1407                        .animation_interval
1408                        .expect("second present should have an animation interval")
1409                        .as_nanos() as u64
1410            );
1411        }
1412    }
1413
1414    #[test]
1415    fn disabling_tracing_clears_frame_events() {
1416        let _trace_test_guard = TraceTestGuard::new();
1417        set_trace_enabled(true);
1418        let window_id = WindowId::from(0xC1EA);
1419        let mut window_profiler =
1420            WindowProfiler::new(window_id).expect("window profiler should initialize");
1421        let mut collector = FrameTimingCollector::new();
1422
1423        window_profiler.begin_draw();
1424        window_profiler.end_draw(None, 0);
1425        assert!(
1426            FRAME_TIMINGS
1427                .lock()
1428                .timings
1429                .iter()
1430                .copied()
1431                .any(|event| event_matches_window(event, window_id))
1432        );
1433
1434        set_trace_enabled(false);
1435        assert!(
1436            collector
1437                .collect_unseen()
1438                .iter()
1439                .all(|event| !event_matches_window(*event, window_id))
1440        );
1441    }
1442
1443    #[cfg(feature = "profiler")]
1444    #[test]
1445    fn records_intervals_only_between_animation_frames() {
1446        let mut window_profiler =
1447            WindowProfiler::new(WindowId::from(1)).expect("window profiler should initialize");
1448        let start = Instant::now();
1449
1450        draw_and_present(&mut window_profiler, start, true, true);
1451        assert_eq!(window_profiler.present_interval_histogram.len(), 0);
1452
1453        draw_and_present(&mut window_profiler, start + FRAME, true, true);
1454        assert_eq!(window_profiler.present_interval_histogram.len(), 1);
1455
1456        draw_and_present(&mut window_profiler, start + FRAME * 2, true, false);
1457        assert_eq!(window_profiler.present_interval_histogram.len(), 2);
1458
1459        draw_and_present(&mut window_profiler, start + FRAME * 100, true, true);
1460        assert_eq!(window_profiler.present_interval_histogram.len(), 2);
1461    }
1462
1463    #[cfg(feature = "profiler")]
1464    #[test]
1465    fn missed_frames_stretch_the_recorded_interval() {
1466        let mut window_profiler =
1467            WindowProfiler::new(WindowId::from(2)).expect("window profiler should initialize");
1468        let start = Instant::now();
1469
1470        draw_and_present(&mut window_profiler, start, true, true);
1471        draw_and_present(&mut window_profiler, start + FRAME * 5, true, true);
1472
1473        let recorded = window_profiler.present_interval_histogram.max();
1474        assert!(recorded >= (FRAME * 4).as_nanos() as u64);
1475    }
1476
1477    #[cfg(feature = "profiler")]
1478    #[test]
1479    fn ignores_re_presents_of_unchanged_frames() {
1480        let mut window_profiler =
1481            WindowProfiler::new(WindowId::from(3)).expect("window profiler should initialize");
1482        let start = Instant::now();
1483
1484        draw_and_present(&mut window_profiler, start, true, true);
1485        window_profiler.record_present_at(start + FRAME / 2, start + FRAME / 2, true, true);
1486        draw_and_present(&mut window_profiler, start + FRAME, true, true);
1487
1488        assert_eq!(window_profiler.present_interval_histogram.len(), 1);
1489        assert!(
1490            window_profiler.present_interval_histogram.max() >= (FRAME * 3 / 4).as_nanos() as u64
1491        );
1492    }
1493
1494    #[cfg(feature = "profiler")]
1495    #[test]
1496    fn skips_intervals_for_inactive_windows() {
1497        let mut window_profiler =
1498            WindowProfiler::new(WindowId::from(4)).expect("window profiler should initialize");
1499        let start = Instant::now();
1500
1501        draw_and_present(&mut window_profiler, start, false, true);
1502        draw_and_present(&mut window_profiler, start + FRAME, false, true);
1503        assert_eq!(window_profiler.present_interval_histogram.len(), 0);
1504
1505        draw_and_present(&mut window_profiler, start + FRAME * 2, true, true);
1506        assert_eq!(window_profiler.present_interval_histogram.len(), 0);
1507
1508        draw_and_present(&mut window_profiler, start + FRAME * 3, true, true);
1509        assert_eq!(window_profiler.present_interval_histogram.len(), 1);
1510    }
1511
1512    #[test]
1513    fn records_dirty_to_present_durations() {
1514        let mut window_profiler =
1515            WindowProfiler::new(WindowId::from(8)).expect("window profiler should initialize");
1516        let draw_end = Instant::now();
1517        let present_end = draw_end + Duration::from_millis(6);
1518
1519        record_test_draw(&mut window_profiler, draw_end);
1520        window_profiler.record_present_at(present_end, present_end, true, false);
1521
1522        let snapshot = window_profiler.frame_duration_snapshot();
1523        let histogram = snapshot.dirty_to_present_histogram;
1524        assert_eq!(histogram.len(), 1);
1525        assert!(histogram.max() >= Duration::from_millis(10).as_nanos() as u64);
1526    }
1527
1528    #[cfg(feature = "profiler")]
1529    #[test]
1530    fn records_every_draw_duration() {
1531        let mut window_profiler =
1532            WindowProfiler::new(WindowId::from(5)).expect("window profiler should initialize");
1533
1534        window_profiler.record_draw_duration(Duration::from_millis(2));
1535        window_profiler.record_draw_duration(Duration::from_millis(40));
1536
1537        let snapshot = window_profiler.frame_duration_snapshot();
1538        assert_eq!(snapshot.draw_duration_histogram.len(), 2);
1539        assert!(snapshot.draw_duration_histogram.max() >= 39_000_000);
1540    }
1541
1542    #[test]
1543    fn records_input_latency_at_the_frame_presentation_timestamp() {
1544        let mut window_profiler =
1545            WindowProfiler::new(WindowId::from(6)).expect("window profiler should initialize");
1546        let first_input_at = Instant::now();
1547        let presented_at = first_input_at + Duration::from_millis(12);
1548
1549        begin_input_at(&mut window_profiler, first_input_at);
1550        window_profiler.end_input(true);
1551        begin_input_at(
1552            &mut window_profiler,
1553            first_input_at + Duration::from_millis(2),
1554        );
1555        window_profiler.end_input(true);
1556        record_test_draw(&mut window_profiler, presented_at);
1557        window_profiler.record_present_at(presented_at, presented_at, true, false);
1558
1559        let snapshot = window_profiler.input_latency_snapshot();
1560        assert_eq!(snapshot.latency_histogram.len(), 1);
1561        assert!(snapshot.latency_histogram.max() >= Duration::from_millis(12).as_nanos() as u64);
1562        assert_eq!(snapshot.events_per_frame_histogram.len(), 1);
1563        assert_eq!(snapshot.events_per_frame_histogram.max(), 2);
1564        assert_eq!(snapshot.mid_draw_events_dropped, 0);
1565    }
1566
1567    #[test]
1568    fn excludes_input_that_arrives_during_a_draw() {
1569        let mut window_profiler =
1570            WindowProfiler::new(WindowId::from(7)).expect("window profiler should initialize");
1571
1572        window_profiler.begin_draw();
1573        begin_input_at(&mut window_profiler, Instant::now());
1574        window_profiler.end_input(true);
1575        window_profiler.end_draw(None, 0);
1576
1577        let snapshot = window_profiler.input_latency_snapshot();
1578        assert!(snapshot.latency_histogram.is_empty());
1579        assert!(snapshot.events_per_frame_histogram.is_empty());
1580        assert_eq!(snapshot.mid_draw_events_dropped, 1);
1581    }
1582
1583    #[test]
1584    fn overlapping_trace_scopes_keep_tracing_enabled() {
1585        let _trace_test_guard = TraceTestGuard::new();
1586        let first_scope = trace_scope();
1587        let second_scope = trace_scope();
1588
1589        assert!(trace_enabled());
1590        drop(first_scope);
1591        assert!(trace_enabled());
1592        drop(second_scope);
1593        assert!(!trace_enabled());
1594    }
1595
1596    const FRAME: Duration = Duration::from_millis(16);
1597
1598    struct TraceTestGuard {
1599        was_enabled: bool,
1600        _lock: MutexGuard<'static, ()>,
1601    }
1602
1603    impl TraceTestGuard {
1604        fn new() -> Self {
1605            let lock = super::trace_test_lock();
1606            let was_enabled = trace_enabled();
1607            set_trace_enabled(false);
1608            Self {
1609                was_enabled,
1610                _lock: lock,
1611            }
1612        }
1613    }
1614
1615    impl Drop for TraceTestGuard {
1616        fn drop(&mut self) {
1617            set_trace_enabled(false);
1618            if self.was_enabled {
1619                set_trace_enabled(true);
1620            }
1621        }
1622    }
1623
1624    fn event_matches_window(event: FrameEvent, window_id: WindowId) -> bool {
1625        match event {
1626            FrameEvent::Draw(timing) => timing.window_id == window_id,
1627            FrameEvent::Present(timing) => timing.window_id == window_id,
1628        }
1629    }
1630
1631    fn begin_input_at(window_profiler: &mut WindowProfiler, started_at: Instant) {
1632        window_profiler
1633            .active_activities
1634            .push(WindowActivity::Input {
1635                started_at,
1636                kind: "test",
1637            });
1638    }
1639
1640    #[cfg(feature = "profiler")]
1641    fn draw_and_present(
1642        window_profiler: &mut WindowProfiler,
1643        presented_at: Instant,
1644        window_active: bool,
1645        next_frame_scheduled: bool,
1646    ) {
1647        record_test_draw(window_profiler, presented_at);
1648        window_profiler.record_present_at(
1649            presented_at,
1650            presented_at,
1651            window_active,
1652            next_frame_scheduled,
1653        );
1654    }
1655
1656    fn record_test_draw(window_profiler: &mut WindowProfiler, draw_end: Instant) {
1657        window_profiler.record_draw_timing(FrameTiming {
1658            window_id: window_profiler.window_id,
1659            dirty_at: Some(draw_end - Duration::from_millis(4)),
1660            invalidations: 1,
1661            draw_start: draw_end - Duration::from_millis(2),
1662            draw_end,
1663        });
1664    }
1665}