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