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