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