Skip to main content

nsh_engine/
perf.rs

1//! Performance monitoring: what a surface's frames and commits cost while it
2//! runs, for an on-screen monitor (`--fps`, `NSH_FPS=1`, the app's
3//! `setFpsEnabled`) or the app's own tooling.
4//!
5//! A [`PerfMonitor`] is shared by the two threads of a surface:
6//!
7//! - the **engine thread** records every wake-up that produced a commit
8//!   (the JS it ran and the core's apply, render and layout,
9//!   [`CommitTiming`]) and how long it was busy at all;
10//! - the **main thread** records the time it spends on the surface
11//!   ([`PerfMonitor::record_work`]: applying batches, ticking animations and
12//!   frame callbacks, handling input) and closes a frame at every display
13//!   refresh ([`PerfMonitor::vsync`]): a refresh in which something changed is
14//!   a frame the screen showed, and its cost is the main-thread work since
15//!   the previous refresh. It also reports how long a batch waited between
16//!   the engine handing it over and the main thread applying it
17//!   ([`PerfMonitor::record_latency`]).
18//!
19//! [`PerfMonitor::snapshot`] turns what was recorded into readings
20//! ([`PerfSnapshot`]); [`ProcessSampler`] reads the process' CPU and memory.
21//!
22//! Nothing is measured while no monitor is installed
23//! ([`crate::EngineControl::set_perf_monitor`]): the engine checks one
24//! `Option` per wake-up, the platforms one per frame.
25//!
26//! The readings follow gpui-kit's `gpui-fps` (the same idea, the same rows):
27//! the headline rate counts frames that reached the screen, `MAX` is derived
28//! from what a frame cost rather than counted (so the monitor never drives
29//! frames to find it), and the first frames, the cold ones, are not counted.
30
31use std::{collections::VecDeque, sync::Mutex, time::Duration};
32
33/// The environment variable that turns the performance monitor on at
34/// launch, whatever started the app (`NSH_FPS=1`), as Metal's
35/// `MTL_HUD_ENABLED=1` does its HUD.
36pub const ENV_VAR: &str = "NSH_FPS";
37
38/// Whether [`ENV_VAR`] asks for the performance monitor: set to anything
39/// but empty, `0` or `false`. The platforms turn their monitor on at launch
40/// when it does, as `--fps` (`AppOptions::fps`) does.
41pub fn enabled_by_env() -> bool {
42    std::env::var_os(ENV_VAR)
43        .is_some_and(|value| !matches!(value.to_str(), Some("" | "0" | "false")))
44}
45
46/// The log target of the readings the platforms log once a second while
47/// the monitor runs (`--fps`). It is not `nsh::perf`, the timings of
48/// `--trace`, so a command line tells the two apart: `nsh run --fps` shows
49/// the panel and logs these lines only with `-v`.
50pub const LOG_TARGET: &str = "nsh::fps";
51
52use nsh_core::time::Instant;
53
54/// Samples kept for the distributions (frames, commits).
55const CAPACITY: usize = 120;
56
57/// The window over which rates (frames, commits per second) are counted.
58const RATE_WINDOW: Duration = Duration::from_secs(1);
59
60/// Frames and commits not counted after the monitor is installed: the
61/// first ones after a start are cold (caches, fonts, the first layout) and
62/// are not what the app costs to run.
63const WARMUP: u32 = 4;
64
65/// What one engine wake-up that committed cost.
66#[derive(Debug, Clone, Copy, Default, PartialEq)]
67pub struct CommitTiming {
68    /// The app's code: JS event handlers, timers, microtasks, list binds
69    /// and the decoding of what they rendered (or a Rust app's tasks): the
70    /// wake-up's time less [`CommitTiming::layout`].
71    pub js: Duration,
72    /// The core: applying the ops, rendering components, typesetting text,
73    /// layout and diffing into mount items.
74    pub layout: Duration,
75    /// Ops applied.
76    pub ops: u32,
77    /// Mount items produced.
78    pub items: u32,
79}
80
81/// Mean, 95th percentile and maximum of a set of durations.
82#[derive(Debug, Clone, Copy, Default, PartialEq)]
83pub struct Stat {
84    /// The mean.
85    pub mean: Duration,
86    /// The median.
87    pub p50: Duration,
88    /// The nearest sample at the 95th percentile.
89    pub p95: Duration,
90    /// The longest.
91    pub max: Duration,
92}
93
94impl Stat {
95    fn of(samples: impl Iterator<Item = Duration>) -> Stat {
96        let mut sorted: Vec<Duration> = samples.collect();
97        if sorted.is_empty() {
98            return Stat::default();
99        }
100        sorted.sort_unstable();
101        let sum: Duration = sorted.iter().sum();
102        let at = |q: f32| ((sorted.len() as f32 * q).ceil() as usize).clamp(1, sorted.len()) - 1;
103        let p95 = at(0.95);
104        Stat {
105            mean: sum / sorted.len() as u32,
106            p50: sorted[at(0.5)],
107            p95: sorted[p95],
108            max: sorted[sorted.len() - 1],
109        }
110    }
111}
112
113/// The process' resource use ([`ProcessSampler`]).
114#[derive(Debug, Clone, Copy, Default, PartialEq)]
115pub struct ProcessSample {
116    /// CPU time over wall time across the last [`CPU_WINDOW`] or so, in
117    /// percent of one core (as `top` and Activity Monitor show it: 150 is
118    /// one and a half cores busy).
119    pub cpu: Option<f32>,
120    /// Memory the process owns, in bytes: the physical footprint on Apple
121    /// platforms (Activity Monitor's Memory column), the resident set
122    /// elsewhere.
123    pub memory: Option<u64>,
124    /// GPU time over wall time, in percent, where the platform tells it
125    /// per process (macOS).
126    pub gpu: Option<f32>,
127}
128
129/// What the app holds, as the engine read it after its last idle
130/// collection.
131#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
132pub struct MemorySample {
133    /// Bytes the JS heap holds (0 without a JS runtime).
134    pub js_heap: u64,
135    /// Live JS objects.
136    pub js_objects: u64,
137    /// Nodes alive in the core, the root included.
138    pub nodes: u64,
139    /// The node ids the core's id table has room for: far above `nodes`
140    /// when the ids of nodes that are gone still take room.
141    pub node_ids: u64,
142}
143
144/// What a [`PerfMonitor`] read, as of one moment.
145#[derive(Debug, Clone, Default, PartialEq)]
146pub struct PerfSnapshot {
147    /// Frames shown per second over the last second: display refreshes in
148    /// which the surface changed. Low while the app is idle, which is not
149    /// slowness.
150    pub fps: f32,
151    /// What the main thread could keep up with: one over the mean frame
152    /// cost, capped at the display's rate when it is known.
153    pub max_fps: f32,
154    /// The rate the display link asks for (Hz: its period), once it ran.
155    pub refresh_rate: Option<f32>,
156    /// The gaps between refreshes as they were delivered, over the last
157    /// [`CAPACITY`]: a mean above one period means refreshes came late or
158    /// were skipped (a main thread busy when they were due).
159    pub tick_interval: Stat,
160    /// The gaps between shown frames over the last [`CAPACITY`] (long while
161    /// the app is idle, one period while it animates smoothly).
162    pub frame_interval: Stat,
163    /// Main-thread time per shown frame (applying batches, animations,
164    /// input), over the last [`CAPACITY`] frames.
165    pub frame: Stat,
166    /// Share of those frames that took longer than one refresh, in `0..=1`.
167    pub dropped: f32,
168    /// Commits per second over the last second.
169    pub commits: f32,
170    /// The app's code per commit.
171    pub js: Stat,
172    /// The core's work per commit.
173    pub layout: Stat,
174    /// Mean mount items per commit.
175    pub items: f32,
176    /// How long batches waited between the engine thread handing them over
177    /// and the main thread applying them.
178    pub latency: Stat,
179    /// The engine thread's busy time over the last second, in percent.
180    pub engine_busy: f32,
181    /// Main-thread cost of the retained frames, oldest first (for a trace).
182    pub frames: Vec<Duration>,
183    /// The process' resource use, as last given to [`PerfMonitor::set_process`].
184    pub process: ProcessSample,
185    /// What the app holds, as last given to [`PerfMonitor::set_memory`]:
186    /// none before the engine's first idle collection.
187    pub memory: Option<MemorySample>,
188}
189
190/// Collects a surface's frame and commit timings. Shared by its engine
191/// thread and its main thread (`Arc`); see the module documentation.
192#[derive(Debug)]
193pub struct PerfMonitor {
194    inner: Mutex<Inner>,
195}
196
197#[derive(Debug)]
198struct Inner {
199    /// Main-thread work since the last refresh, and whether it changed
200    /// anything.
201    pending: Duration,
202    dirty: bool,
203    /// Shown frames: when, and their main-thread cost.
204    frames: VecDeque<(Instant, Duration)>,
205    frame_warmup: u32,
206    refresh: Option<f32>,
207    /// The previous refresh, and the gaps between refreshes as they were
208    /// delivered (a late or skipped one shows as a long gap).
209    last_vsync: Option<Instant>,
210    ticks: VecDeque<Duration>,
211    commits: VecDeque<(Instant, CommitTiming)>,
212    commit_warmup: u32,
213    latencies: VecDeque<Duration>,
214    /// Engine wake-ups: when they ended, and how long they were busy.
215    busy: VecDeque<(Instant, Duration)>,
216    process: ProcessSample,
217    memory: Option<MemorySample>,
218}
219
220impl Default for PerfMonitor {
221    fn default() -> Self {
222        PerfMonitor {
223            inner: Mutex::new(Inner {
224                pending: Duration::ZERO,
225                dirty: false,
226                frames: VecDeque::with_capacity(CAPACITY),
227                frame_warmup: WARMUP,
228                refresh: None,
229                last_vsync: None,
230                ticks: VecDeque::with_capacity(CAPACITY),
231                commits: VecDeque::with_capacity(CAPACITY),
232                commit_warmup: WARMUP,
233                latencies: VecDeque::with_capacity(CAPACITY),
234                busy: VecDeque::new(),
235                process: ProcessSample::default(),
236                memory: None,
237            }),
238        }
239    }
240}
241
242fn push<T>(queue: &mut VecDeque<T>, value: T) {
243    if queue.len() == CAPACITY {
244        queue.pop_front();
245    }
246    queue.push_back(value);
247}
248
249impl PerfMonitor {
250    /// An empty monitor.
251    pub fn new() -> PerfMonitor {
252        PerfMonitor::default()
253    }
254
255    fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
256        self.inner.lock().unwrap_or_else(|e| e.into_inner())
257    }
258
259    /// Main thread: `cost` was spent on the surface; `dirty` if it changed
260    /// what the screen shows (a batch was applied, an animation stepped, a
261    /// scroll view moved).
262    pub fn record_work(&self, cost: Duration, dirty: bool) {
263        let mut inner = self.lock();
264        inner.pending += cost;
265        inner.dirty |= dirty;
266    }
267
268    /// Main thread: the display refreshed at `at`, `interval` after the
269    /// previous refresh (the display link's period). Closes the frame the
270    /// work since the previous refresh belongs to.
271    pub fn vsync(&self, at: Instant, interval: Duration) {
272        let mut inner = self.lock();
273        if interval > Duration::ZERO {
274            let rate = 1.0 / interval.as_secs_f32();
275            // Smoothed: a link's period is exact, a measured one jitters.
276            inner.refresh = Some(match inner.refresh {
277                Some(r) if (r - rate).abs() < r * 0.1 => r + (rate - r) * 0.1,
278                _ => rate,
279            });
280        }
281        if let Some(last) = inner.last_vsync.replace(at) {
282            let gap = at.duration_since(last);
283            // A pause (nothing wanted frames, the link stopped) is not a
284            // late refresh.
285            if gap < Duration::from_millis(100) {
286                push(&mut inner.ticks, gap);
287            }
288        }
289        let cost = std::mem::take(&mut inner.pending);
290        if !std::mem::take(&mut inner.dirty) {
291            return;
292        }
293        if inner.frame_warmup > 0 {
294            inner.frame_warmup -= 1;
295            return;
296        }
297        push(&mut inner.frames, (at, cost));
298    }
299
300    /// Main thread: a batch was applied `latency` after the engine handed
301    /// it over.
302    pub fn record_latency(&self, latency: Duration) {
303        let mut inner = self.lock();
304        // The first batches wait for the cold first frames.
305        if inner.frame_warmup == 0 {
306            push(&mut inner.latencies, latency);
307        }
308    }
309
310    /// Engine thread: a wake-up that committed.
311    pub fn record_commit(&self, timing: CommitTiming) {
312        let mut inner = self.lock();
313        if inner.commit_warmup > 0 {
314            inner.commit_warmup -= 1;
315            return;
316        }
317        push(&mut inner.commits, (Instant::now(), timing));
318    }
319
320    /// Engine thread: a wake-up was busy for `busy`.
321    pub fn record_busy(&self, busy: Duration) {
322        let now = Instant::now();
323        let mut inner = self.lock();
324        inner.busy.push_back((now, busy));
325        while inner
326            .busy
327            .front()
328            .is_some_and(|&(at, _)| now.duration_since(at) > RATE_WINDOW)
329        {
330            inner.busy.pop_front();
331        }
332    }
333
334    /// Stores the process' latest resource use ([`ProcessSampler`]), shown
335    /// with the next snapshots.
336    pub fn set_process(&self, sample: ProcessSample) {
337        self.lock().process = sample;
338    }
339
340    /// Engine thread: what the app holds, shown with the next snapshots.
341    pub fn set_memory(&self, sample: MemorySample) {
342        self.lock().memory = Some(sample);
343    }
344
345    /// The readings as of now.
346    pub fn snapshot(&self) -> PerfSnapshot {
347        let now = Instant::now();
348        let inner = self.lock();
349        let recent = |at: Instant| now.duration_since(at) <= RATE_WINDOW;
350        // `n` frames span `n - 1` intervals: the rate is measured over the
351        // span they cover, which keeps it right before the window fills.
352        let shown: Vec<Instant> = inner
353            .frames
354            .iter()
355            .map(|&(at, _)| at)
356            .filter(|&at| recent(at))
357            .collect();
358        let fps = match (shown.first(), shown.last()) {
359            (Some(&first), Some(&last)) if shown.len() >= 2 && last > first => {
360                // The span to now when the frames stopped: an app that went
361                // idle reads as fewer frames, not as its last burst.
362                let span = now.duration_since(first).max(last.duration_since(first));
363                (shown.len() - 1) as f32 / span.as_secs_f32()
364            }
365            _ => 0.0,
366        };
367        let frame = Stat::of(inner.frames.iter().map(|&(_, cost)| cost));
368        let budget = Duration::from_secs_f32(1.0 / inner.refresh.unwrap_or(60.0));
369        let dropped = match inner.frames.len() {
370            0 => 0.0,
371            n => {
372                inner
373                    .frames
374                    .iter()
375                    .filter(|&&(_, cost)| cost > budget)
376                    .count() as f32
377                    / n as f32
378            }
379        };
380        let max_fps = if frame.mean > Duration::ZERO {
381            let max = 1.0 / frame.mean.as_secs_f32();
382            inner.refresh.map_or(max, |r| max.min(r))
383        } else {
384            0.0
385        };
386        let commits = inner.commits.iter().filter(|&&(at, _)| recent(at)).count() as f32;
387        let items = match inner.commits.len() {
388            0 => 0.0,
389            n => {
390                inner
391                    .commits
392                    .iter()
393                    .map(|(_, c)| c.items as f32)
394                    .sum::<f32>()
395                    / n as f32
396            }
397        };
398        let busy: Duration = inner
399            .busy
400            .iter()
401            .filter(|&&(at, _)| recent(at))
402            .map(|&(_, d)| d)
403            .sum();
404        PerfSnapshot {
405            fps,
406            max_fps,
407            refresh_rate: inner.refresh,
408            tick_interval: Stat::of(inner.ticks.iter().copied()),
409            frame_interval: Stat::of(
410                inner
411                    .frames
412                    .iter()
413                    .zip(inner.frames.iter().skip(1))
414                    .map(|(&(a, _), &(b, _))| b.duration_since(a)),
415            ),
416            frame,
417            dropped,
418            commits,
419            js: Stat::of(inner.commits.iter().map(|(_, c)| c.js)),
420            layout: Stat::of(inner.commits.iter().map(|(_, c)| c.layout)),
421            items,
422            latency: Stat::of(inner.latencies.iter().copied()),
423            engine_busy: busy.as_secs_f32() / RATE_WINDOW.as_secs_f32() * 100.0,
424            frames: inner.frames.iter().map(|&(_, cost)| cost).collect(),
425            process: inner.process,
426            memory: inner.memory,
427        }
428    }
429}
430
431/// How much time a CPU reading spans at least: a rate over a shorter span
432/// is mostly the work that happened to run in it. Monitors sample from
433/// more than one place (a timer redrawing the panel, the frame that
434/// redraw makes), so two samples can be a frame apart, and a rate over
435/// that frame alone reads a core busy while the app idles.
436pub const CPU_WINDOW: Duration = Duration::from_secs(1);
437
438/// The shortest span a CPU reading is given over at all (before
439/// [`CPU_WINDOW`] has passed since the first sample).
440const CPU_MIN_SPAN: Duration = Duration::from_millis(250);
441
442/// Reads the process' CPU and memory use. CPU use is a rate: the CPU time
443/// over the wall time since the newest earlier sample at least
444/// [`CPU_WINDOW`] old (the oldest one until then), whenever and however
445/// often it is sampled; none until a quarter of a second has passed.
446#[derive(Debug)]
447pub struct ProcessSampler {
448    /// Earlier readings of the CPU time and when they were taken, oldest
449    /// first: the first is the newest at least [`CPU_WINDOW`] old.
450    readings: VecDeque<(Duration, Instant)>,
451}
452
453impl Default for ProcessSampler {
454    fn default() -> Self {
455        ProcessSampler::new()
456    }
457}
458
459impl ProcessSampler {
460    /// A sampler with no reading yet.
461    pub fn new() -> ProcessSampler {
462        ProcessSampler {
463            readings: VecDeque::new(),
464        }
465    }
466
467    /// The process' CPU and memory use now (GPU use is the platform's to
468    /// add).
469    pub fn sample(&mut self) -> ProcessSample {
470        let now = Instant::now();
471        ProcessSample {
472            cpu: cpu_time().and_then(|used| self.rate(used, now)),
473            memory: memory(),
474            gpu: None,
475        }
476    }
477
478    /// Records `used` CPU time at `now` and returns the rate over the
479    /// window, in percent of one core.
480    fn rate(&mut self, used: Duration, now: Instant) -> Option<f32> {
481        self.readings.push_back((used, now));
482        while self
483            .readings
484            .get(1)
485            .is_some_and(|(_, at)| now.duration_since(*at) >= CPU_WINDOW)
486        {
487            self.readings.pop_front();
488        }
489        let (base, at) = *self.readings.front()?;
490        let span = now.duration_since(at);
491        (span >= CPU_MIN_SPAN)
492            .then(|| used.saturating_sub(base).as_secs_f32() / span.as_secs_f32() * 100.0)
493    }
494}
495
496/// The CPU time (user and system) the process used so far.
497#[cfg(unix)]
498fn cpu_time() -> Option<Duration> {
499    let mut usage = std::mem::MaybeUninit::<libc::rusage>::uninit();
500    // SAFETY: `usage` is a buffer of the layout the call fills.
501    if unsafe { libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) } != 0 {
502        return None;
503    }
504    // SAFETY: a zero return means the call filled the buffer.
505    let usage = unsafe { usage.assume_init() };
506    let time = |t: libc::timeval| Duration::new(t.tv_sec as u64, t.tv_usec as u32 * 1000);
507    Some(time(usage.ru_utime) + time(usage.ru_stime))
508}
509
510#[cfg(windows)]
511fn cpu_time() -> Option<Duration> {
512    use windows_sys::Win32::{
513        Foundation::FILETIME,
514        System::Threading::{GetCurrentProcess, GetProcessTimes},
515    };
516    let zero = FILETIME {
517        dwLowDateTime: 0,
518        dwHighDateTime: 0,
519    };
520    let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero);
521    // SAFETY: the pseudo handle of this process and four buffers the call fills.
522    let ok = unsafe {
523        GetProcessTimes(
524            GetCurrentProcess(),
525            &mut created,
526            &mut exited,
527            &mut kernel,
528            &mut user,
529        )
530    };
531    // FILETIME counts 100 ns.
532    let ticks = |t: FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime);
533    (ok != 0).then(|| Duration::from_nanos((ticks(kernel) + ticks(user)) * 100))
534}
535
536#[cfg(not(any(unix, windows)))]
537fn cpu_time() -> Option<Duration> {
538    None
539}
540
541/// The physical footprint (`task_info`'s `TASK_VM_INFO`): the dirty and
542/// compressed memory the process owns, what Activity Monitor shows and what
543/// the system judges it by under memory pressure (unlike the resident size,
544/// it leaves out the frameworks' clean pages every process maps). Mach's
545/// `task_info` is public on every Apple platform; libproc's
546/// `proc_pid_rusage`, which reads the same number, has no header in the iOS
547/// SDK, and App Store review can reject iOS apps for calls outside it.
548#[cfg(target_vendor = "apple")]
549fn memory() -> Option<u64> {
550    /// `struct task_vm_info` (`mach/task_info.h`) as far as
551    /// `phys_footprint`, the fields `TASK_VM_INFO_REV1_COUNT` covers; the
552    /// `libc` crate does not declare it.
553    #[repr(C)]
554    struct TaskVmInfo {
555        /// `virtual_size` to `compressed_lifetime`: two `integer_t`s and
556        /// seventeen `mach_vm_size_t`s, 144 bytes.
557        before: [u64; 18],
558        phys_footprint: u64,
559    }
560    unsafe extern "C" {
561        // The task's own port (`mach_init.h`, whose `mach_task_self()` is a
562        // macro reading it); the `libc` crate wraps it for macOS only.
563        static mach_task_self_: libc::mach_port_t;
564    }
565    const TASK_VM_INFO: libc::task_flavor_t = 22;
566    const _: () = assert!(std::mem::size_of::<TaskVmInfo>() == 152);
567    let words = std::mem::size_of::<TaskVmInfo>() / std::mem::size_of::<libc::natural_t>();
568    let mut count = words as libc::mach_msg_type_number_t;
569    let mut info = std::mem::MaybeUninit::<TaskVmInfo>::uninit();
570    // SAFETY: `mach_task_self_` is set before any code runs and never
571    // changes; `info` has room for `count` words, the most the call writes,
572    // and `count` says how many it wrote.
573    let status = unsafe {
574        libc::task_info(
575            mach_task_self_,
576            TASK_VM_INFO,
577            info.as_mut_ptr().cast::<libc::integer_t>(),
578            &mut count,
579        )
580    };
581    // SAFETY: success with every word asked for filled the whole buffer.
582    (status == libc::KERN_SUCCESS && count as usize == words)
583        .then(|| unsafe { info.assume_init() }.phys_footprint)
584}
585
586/// The resident set (`/proc/self/statm`'s second field, in pages).
587#[cfg(any(target_os = "linux", target_os = "android"))]
588fn memory() -> Option<u64> {
589    let statm = std::fs::read_to_string("/proc/self/statm").ok()?;
590    let pages: u64 = statm.split_whitespace().nth(1)?.parse().ok()?;
591    // SAFETY: a plain query of the page size.
592    let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
593    Some(pages * u64::try_from(page).ok()?)
594}
595
596/// The working set (resident memory), as on Linux.
597#[cfg(windows)]
598fn memory() -> Option<u64> {
599    use windows_sys::Win32::System::{
600        ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS},
601        Threading::GetCurrentProcess,
602    };
603    // SAFETY: all-integer struct, zero is a valid value.
604    let mut counters: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() };
605    counters.cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
606    // SAFETY: the pseudo handle of this process and a buffer of the size `cb` names.
607    let ok = unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) };
608    (ok != 0).then_some(counters.WorkingSetSize as u64)
609}
610
611#[cfg(not(any(
612    target_vendor = "apple",
613    target_os = "linux",
614    target_os = "android",
615    windows
616)))]
617fn memory() -> Option<u64> {
618    None
619}
620
621#[cfg(test)]
622mod tests {
623    use super::*;
624
625    fn ms(ms: u64) -> Duration {
626        Duration::from_millis(ms)
627    }
628
629    #[test]
630    fn stat_of_samples() {
631        let stat = Stat::of((1..=20).map(ms));
632        assert_eq!(stat.mean, Duration::from_micros(10_500));
633        assert_eq!(stat.p50, ms(10));
634        assert_eq!(stat.p95, ms(19));
635        assert_eq!(stat.max, ms(20));
636        assert_eq!(Stat::of(std::iter::empty()), Stat::default());
637    }
638
639    #[test]
640    fn frames_are_refreshes_that_changed_something() {
641        let monitor = PerfMonitor::new();
642        let start = Instant::now();
643        let period = Duration::from_micros(8333);
644        for i in 0..(WARMUP + 10) {
645            monitor.record_work(ms(1), true);
646            // Work that changed nothing is part of the next frame's cost.
647            monitor.record_work(ms(1), false);
648            monitor.vsync(start + period * i, period);
649            // A refresh with nothing new is not a frame.
650            monitor.vsync(start + period * i + period / 2, period);
651        }
652        let snapshot = monitor.snapshot();
653        assert_eq!(snapshot.frames.len(), 10);
654        assert_eq!(snapshot.frame.mean, ms(2));
655        assert!((snapshot.refresh_rate.unwrap() - 120.0).abs() < 0.5);
656        // 2ms frames could run at 500 per second, but not on a 120 Hz display.
657        assert!((snapshot.max_fps - 120.0).abs() < 0.5);
658        assert_eq!(snapshot.dropped, 0.0);
659    }
660
661    #[test]
662    fn slow_frames_are_dropped_ones() {
663        let monitor = PerfMonitor::new();
664        let start = Instant::now();
665        let period = ms(16);
666        for i in 0..(WARMUP + 4) {
667            monitor.record_work(if i % 2 == 0 { ms(20) } else { ms(1) }, true);
668            monitor.vsync(start + period * i, period);
669        }
670        assert_eq!(monitor.snapshot().dropped, 0.5);
671    }
672
673    #[test]
674    fn commits_after_warmup() {
675        let monitor = PerfMonitor::new();
676        for _ in 0..(WARMUP + 3) {
677            monitor.record_commit(CommitTiming {
678                js: ms(1),
679                layout: ms(2),
680                ops: 3,
681                items: 4,
682            });
683        }
684        let snapshot = monitor.snapshot();
685        assert_eq!(snapshot.commits, 3.0);
686        assert_eq!(snapshot.js.mean, ms(1));
687        assert_eq!(snapshot.layout.p95, ms(2));
688        assert_eq!(snapshot.items, 4.0);
689    }
690
691    #[test]
692    fn process_sample_reads_memory() {
693        let mut sampler = ProcessSampler::new();
694        let first = sampler.sample();
695        assert_eq!(first.cpu, None);
696        #[cfg(any(target_vendor = "apple", target_os = "linux"))]
697        assert!(first.memory.is_some_and(|m| m > 0));
698        std::thread::sleep(CPU_MIN_SPAN);
699        #[cfg(unix)]
700        assert!(sampler.sample().cpu.is_some());
701    }
702
703    /// A sample a frame after another reads the rate over the window, not
704    /// over that frame: an idle app sampled by its panel's timer and again
705    /// by the frame that redraw makes is idle.
706    #[test]
707    fn cpu_is_a_rate_over_the_window() {
708        let mut sampler = ProcessSampler::new();
709        let start = Instant::now();
710        let at = |ms: u64| start + Duration::from_millis(ms);
711        let near = |rate: Option<f32>, expected: f64| {
712            rate.is_some_and(|r| (r as f64 - expected).abs() < 0.01)
713        };
714        assert_eq!(sampler.rate(ms(0), at(0)), None);
715        // Too short a span to say.
716        assert_eq!(sampler.rate(ms(5), at(10)), None);
717        assert!(near(sampler.rate(ms(50), at(500)), 10.0));
718        // Idle, then sampled twice 4ms apart, the second after a 4ms frame:
719        // about 10%, not the 100% of that frame alone.
720        assert!(near(sampler.rate(ms(100), at(1000)), 10.0));
721        assert!(near(
722            sampler.rate(ms(104), at(1004)),
723            104.0 / 1004.0 * 100.0
724        ));
725        // Past the window, older readings go: a busy second reads busy.
726        sampler.rate(ms(1100), at(2000));
727        assert!(near(sampler.rate(ms(2100), at(3000)), 100.0));
728    }
729
730    /// `task_info`'s footprint is the one `proc_pid_rusage` reported (the
731    /// two are read a moment apart, so they may differ by what was mapped
732    /// in between).
733    #[cfg(target_os = "macos")]
734    #[test]
735    fn footprint_matches_proc_pid_rusage() {
736        let ours = super::memory().expect("task_info");
737        let mut info = std::mem::MaybeUninit::<libc::rusage_info_v2>::uninit();
738        // SAFETY: `info` is a buffer of exactly the layout `RUSAGE_INFO_V2`
739        // names, the only thing the call writes.
740        let status = unsafe {
741            libc::proc_pid_rusage(
742                std::process::id() as libc::c_int,
743                libc::RUSAGE_INFO_V2,
744                info.as_mut_ptr().cast::<libc::rusage_info_t>(),
745            )
746        };
747        assert_eq!(status, 0);
748        // SAFETY: a zero return means the call filled the buffer.
749        let theirs = unsafe { info.assume_init() }.ri_phys_footprint;
750        assert!(ours.abs_diff(theirs) < 8 << 20, "{ours} vs {theirs}");
751    }
752}