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`) or the app's own tooling.
3//!
4//! A [`PerfMonitor`] is shared by the two threads of a surface:
5//!
6//! - the **engine thread** records every wake-up that produced a commit
7//!   (the JS it ran and the core's apply, render and layout,
8//!   [`CommitTiming`]) and how long it was busy at all;
9//! - the **main thread** records the time it spends on the surface
10//!   ([`PerfMonitor::record_work`]: applying batches, ticking animations and
11//!   frame callbacks, handling input) and closes a frame at every display
12//!   refresh ([`PerfMonitor::vsync`]): a refresh in which something changed is
13//!   a frame the screen showed, and its cost is the main-thread work since
14//!   the previous refresh. It also reports how long a batch waited between
15//!   the engine handing it over and the main thread applying it
16//!   ([`PerfMonitor::record_latency`]).
17//!
18//! [`PerfMonitor::snapshot`] turns what was recorded into readings
19//! ([`PerfSnapshot`]); [`ProcessSampler`] reads the process' CPU and memory.
20//!
21//! Nothing is measured while no monitor is installed
22//! ([`crate::EngineControl::set_perf_monitor`]): the engine checks one
23//! `Option` per wake-up, the platforms one per frame.
24//!
25//! The readings follow gpui-kit's `gpui-fps` (the same idea, the same rows):
26//! the headline rate counts frames that reached the screen, `MAX` is derived
27//! from what a frame cost rather than counted (so the monitor never drives
28//! frames to find it), and the first frames, the cold ones, are not counted.
29
30use std::{collections::VecDeque, sync::Mutex, time::Duration};
31
32use nsh_core::time::Instant;
33
34/// Samples kept for the distributions (frames, commits).
35const CAPACITY: usize = 120;
36
37/// The window over which rates (frames, commits per second) are counted.
38const RATE_WINDOW: Duration = Duration::from_secs(1);
39
40/// Frames and commits not counted after the monitor is installed: the
41/// first ones after a start are cold (caches, fonts, the first layout) and
42/// are not what the app costs to run.
43const WARMUP: u32 = 4;
44
45/// What one engine wake-up that committed cost.
46#[derive(Debug, Clone, Copy, Default, PartialEq)]
47pub struct CommitTiming {
48    /// The app's code: JS event handlers, timers, microtasks, list binds
49    /// and the decoding of what they rendered (or a Rust app's tasks): the
50    /// wake-up's time less [`CommitTiming::layout`].
51    pub js: Duration,
52    /// The core: applying the ops, rendering components, typesetting text,
53    /// layout and diffing into mount items.
54    pub layout: Duration,
55    /// Ops applied.
56    pub ops: u32,
57    /// Mount items produced.
58    pub items: u32,
59}
60
61/// Mean, 95th percentile and maximum of a set of durations.
62#[derive(Debug, Clone, Copy, Default, PartialEq)]
63pub struct Stat {
64    /// The mean.
65    pub mean: Duration,
66    /// The median.
67    pub p50: Duration,
68    /// The nearest sample at the 95th percentile.
69    pub p95: Duration,
70    /// The longest.
71    pub max: Duration,
72}
73
74impl Stat {
75    fn of(samples: impl Iterator<Item = Duration>) -> Stat {
76        let mut sorted: Vec<Duration> = samples.collect();
77        if sorted.is_empty() {
78            return Stat::default();
79        }
80        sorted.sort_unstable();
81        let sum: Duration = sorted.iter().sum();
82        let at = |q: f32| ((sorted.len() as f32 * q).ceil() as usize).clamp(1, sorted.len()) - 1;
83        let p95 = at(0.95);
84        Stat {
85            mean: sum / sorted.len() as u32,
86            p50: sorted[at(0.5)],
87            p95: sorted[p95],
88            max: sorted[sorted.len() - 1],
89        }
90    }
91}
92
93/// The process' resource use ([`ProcessSampler`]).
94#[derive(Debug, Clone, Copy, Default, PartialEq)]
95pub struct ProcessSample {
96    /// CPU time over wall time since the previous sample, in percent of one
97    /// core (as `top` and Activity Monitor show it: 150 is one and a half
98    /// cores busy).
99    pub cpu: Option<f32>,
100    /// Memory the process owns, in bytes: the physical footprint on Apple
101    /// platforms (Activity Monitor's Memory column), the resident set
102    /// elsewhere.
103    pub memory: Option<u64>,
104    /// GPU time over wall time, in percent, where the platform tells it
105    /// per process (macOS).
106    pub gpu: Option<f32>,
107}
108
109/// What a [`PerfMonitor`] read, as of one moment.
110#[derive(Debug, Clone, Default, PartialEq)]
111pub struct PerfSnapshot {
112    /// Frames shown per second over the last second: display refreshes in
113    /// which the surface changed. Low while the app is idle, which is not
114    /// slowness.
115    pub fps: f32,
116    /// What the main thread could keep up with: one over the mean frame
117    /// cost, capped at the display's rate when it is known.
118    pub max_fps: f32,
119    /// The rate the display link asks for (Hz: its period), once it ran.
120    pub refresh_rate: Option<f32>,
121    /// The gaps between refreshes as they were delivered, over the last
122    /// [`CAPACITY`]: a mean above one period means refreshes came late or
123    /// were skipped (a main thread busy when they were due).
124    pub tick_interval: Stat,
125    /// The gaps between shown frames over the last [`CAPACITY`] (long while
126    /// the app is idle, one period while it animates smoothly).
127    pub frame_interval: Stat,
128    /// Main-thread time per shown frame (applying batches, animations,
129    /// input), over the last [`CAPACITY`] frames.
130    pub frame: Stat,
131    /// Share of those frames that took longer than one refresh, in `0..=1`.
132    pub dropped: f32,
133    /// Commits per second over the last second.
134    pub commits: f32,
135    /// The app's code per commit.
136    pub js: Stat,
137    /// The core's work per commit.
138    pub layout: Stat,
139    /// Mean mount items per commit.
140    pub items: f32,
141    /// How long batches waited between the engine thread handing them over
142    /// and the main thread applying them.
143    pub latency: Stat,
144    /// The engine thread's busy time over the last second, in percent.
145    pub engine_busy: f32,
146    /// Main-thread cost of the retained frames, oldest first (for a trace).
147    pub frames: Vec<Duration>,
148    /// The process' resource use, as last given to [`PerfMonitor::set_process`].
149    pub process: ProcessSample,
150}
151
152/// Collects a surface's frame and commit timings. Shared by its engine
153/// thread and its main thread (`Arc`); see the module documentation.
154#[derive(Debug)]
155pub struct PerfMonitor {
156    inner: Mutex<Inner>,
157}
158
159#[derive(Debug)]
160struct Inner {
161    /// Main-thread work since the last refresh, and whether it changed
162    /// anything.
163    pending: Duration,
164    dirty: bool,
165    /// Shown frames: when, and their main-thread cost.
166    frames: VecDeque<(Instant, Duration)>,
167    frame_warmup: u32,
168    refresh: Option<f32>,
169    /// The previous refresh, and the gaps between refreshes as they were
170    /// delivered (a late or skipped one shows as a long gap).
171    last_vsync: Option<Instant>,
172    ticks: VecDeque<Duration>,
173    commits: VecDeque<(Instant, CommitTiming)>,
174    commit_warmup: u32,
175    latencies: VecDeque<Duration>,
176    /// Engine wake-ups: when they ended, and how long they were busy.
177    busy: VecDeque<(Instant, Duration)>,
178    process: ProcessSample,
179}
180
181impl Default for PerfMonitor {
182    fn default() -> Self {
183        PerfMonitor {
184            inner: Mutex::new(Inner {
185                pending: Duration::ZERO,
186                dirty: false,
187                frames: VecDeque::with_capacity(CAPACITY),
188                frame_warmup: WARMUP,
189                refresh: None,
190                last_vsync: None,
191                ticks: VecDeque::with_capacity(CAPACITY),
192                commits: VecDeque::with_capacity(CAPACITY),
193                commit_warmup: WARMUP,
194                latencies: VecDeque::with_capacity(CAPACITY),
195                busy: VecDeque::new(),
196                process: ProcessSample::default(),
197            }),
198        }
199    }
200}
201
202fn push<T>(queue: &mut VecDeque<T>, value: T) {
203    if queue.len() == CAPACITY {
204        queue.pop_front();
205    }
206    queue.push_back(value);
207}
208
209impl PerfMonitor {
210    /// An empty monitor.
211    pub fn new() -> PerfMonitor {
212        PerfMonitor::default()
213    }
214
215    fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
216        self.inner.lock().unwrap_or_else(|e| e.into_inner())
217    }
218
219    /// Main thread: `cost` was spent on the surface; `dirty` if it changed
220    /// what the screen shows (a batch was applied, an animation stepped, a
221    /// scroll view moved).
222    pub fn record_work(&self, cost: Duration, dirty: bool) {
223        let mut inner = self.lock();
224        inner.pending += cost;
225        inner.dirty |= dirty;
226    }
227
228    /// Main thread: the display refreshed at `at`, `interval` after the
229    /// previous refresh (the display link's period). Closes the frame the
230    /// work since the previous refresh belongs to.
231    pub fn vsync(&self, at: Instant, interval: Duration) {
232        let mut inner = self.lock();
233        if interval > Duration::ZERO {
234            let rate = 1.0 / interval.as_secs_f32();
235            // Smoothed: a link's period is exact, a measured one jitters.
236            inner.refresh = Some(match inner.refresh {
237                Some(r) if (r - rate).abs() < r * 0.1 => r + (rate - r) * 0.1,
238                _ => rate,
239            });
240        }
241        if let Some(last) = inner.last_vsync.replace(at) {
242            let gap = at.duration_since(last);
243            // A pause (nothing wanted frames, the link stopped) is not a
244            // late refresh.
245            if gap < Duration::from_millis(100) {
246                push(&mut inner.ticks, gap);
247            }
248        }
249        let cost = std::mem::take(&mut inner.pending);
250        if !std::mem::take(&mut inner.dirty) {
251            return;
252        }
253        if inner.frame_warmup > 0 {
254            inner.frame_warmup -= 1;
255            return;
256        }
257        push(&mut inner.frames, (at, cost));
258    }
259
260    /// Main thread: a batch was applied `latency` after the engine handed
261    /// it over.
262    pub fn record_latency(&self, latency: Duration) {
263        let mut inner = self.lock();
264        // The first batches wait for the cold first frames.
265        if inner.frame_warmup == 0 {
266            push(&mut inner.latencies, latency);
267        }
268    }
269
270    /// Engine thread: a wake-up that committed.
271    pub fn record_commit(&self, timing: CommitTiming) {
272        let mut inner = self.lock();
273        if inner.commit_warmup > 0 {
274            inner.commit_warmup -= 1;
275            return;
276        }
277        push(&mut inner.commits, (Instant::now(), timing));
278    }
279
280    /// Engine thread: a wake-up was busy for `busy`.
281    pub fn record_busy(&self, busy: Duration) {
282        let now = Instant::now();
283        let mut inner = self.lock();
284        inner.busy.push_back((now, busy));
285        while inner
286            .busy
287            .front()
288            .is_some_and(|&(at, _)| now.duration_since(at) > RATE_WINDOW)
289        {
290            inner.busy.pop_front();
291        }
292    }
293
294    /// Stores the process' latest resource use ([`ProcessSampler`]), shown
295    /// with the next snapshots.
296    pub fn set_process(&self, sample: ProcessSample) {
297        self.lock().process = sample;
298    }
299
300    /// The readings as of now.
301    pub fn snapshot(&self) -> PerfSnapshot {
302        let now = Instant::now();
303        let inner = self.lock();
304        let recent = |at: Instant| now.duration_since(at) <= RATE_WINDOW;
305        // `n` frames span `n - 1` intervals: the rate is measured over the
306        // span they cover, which keeps it right before the window fills.
307        let shown: Vec<Instant> = inner
308            .frames
309            .iter()
310            .map(|&(at, _)| at)
311            .filter(|&at| recent(at))
312            .collect();
313        let fps = match (shown.first(), shown.last()) {
314            (Some(&first), Some(&last)) if shown.len() >= 2 && last > first => {
315                // The span to now when the frames stopped: an app that went
316                // idle reads as fewer frames, not as its last burst.
317                let span = now.duration_since(first).max(last.duration_since(first));
318                (shown.len() - 1) as f32 / span.as_secs_f32()
319            }
320            _ => 0.0,
321        };
322        let frame = Stat::of(inner.frames.iter().map(|&(_, cost)| cost));
323        let budget = Duration::from_secs_f32(1.0 / inner.refresh.unwrap_or(60.0));
324        let dropped = match inner.frames.len() {
325            0 => 0.0,
326            n => {
327                inner
328                    .frames
329                    .iter()
330                    .filter(|&&(_, cost)| cost > budget)
331                    .count() as f32
332                    / n as f32
333            }
334        };
335        let max_fps = if frame.mean > Duration::ZERO {
336            let max = 1.0 / frame.mean.as_secs_f32();
337            inner.refresh.map_or(max, |r| max.min(r))
338        } else {
339            0.0
340        };
341        let commits = inner.commits.iter().filter(|&&(at, _)| recent(at)).count() as f32;
342        let items = match inner.commits.len() {
343            0 => 0.0,
344            n => {
345                inner
346                    .commits
347                    .iter()
348                    .map(|(_, c)| c.items as f32)
349                    .sum::<f32>()
350                    / n as f32
351            }
352        };
353        let busy: Duration = inner
354            .busy
355            .iter()
356            .filter(|&&(at, _)| recent(at))
357            .map(|&(_, d)| d)
358            .sum();
359        PerfSnapshot {
360            fps,
361            max_fps,
362            refresh_rate: inner.refresh,
363            tick_interval: Stat::of(inner.ticks.iter().copied()),
364            frame_interval: Stat::of(
365                inner
366                    .frames
367                    .iter()
368                    .zip(inner.frames.iter().skip(1))
369                    .map(|(&(a, _), &(b, _))| b.duration_since(a)),
370            ),
371            frame,
372            dropped,
373            commits,
374            js: Stat::of(inner.commits.iter().map(|(_, c)| c.js)),
375            layout: Stat::of(inner.commits.iter().map(|(_, c)| c.layout)),
376            items,
377            latency: Stat::of(inner.latencies.iter().copied()),
378            engine_busy: busy.as_secs_f32() / RATE_WINDOW.as_secs_f32() * 100.0,
379            frames: inner.frames.iter().map(|&(_, cost)| cost).collect(),
380            process: inner.process,
381        }
382    }
383}
384
385/// Reads the process' CPU and memory use. CPU use is a rate: each
386/// [`ProcessSampler::sample`] reports the CPU time since the previous one
387/// over the wall time between them (the first reports none).
388#[derive(Debug)]
389pub struct ProcessSampler {
390    last: Option<(Duration, Instant)>,
391}
392
393impl Default for ProcessSampler {
394    fn default() -> Self {
395        ProcessSampler::new()
396    }
397}
398
399impl ProcessSampler {
400    /// A sampler with no reading yet.
401    pub fn new() -> ProcessSampler {
402        ProcessSampler { last: None }
403    }
404
405    /// The process' CPU and memory use now (GPU use is the platform's to
406    /// add).
407    pub fn sample(&mut self) -> ProcessSample {
408        let now = Instant::now();
409        let cpu = cpu_time().and_then(|used| {
410            let (previous, at) = self.last.replace((used, now))?;
411            let wall = now.duration_since(at).as_secs_f32();
412            (wall > 0.0).then(|| used.saturating_sub(previous).as_secs_f32() / wall * 100.0)
413        });
414        ProcessSample {
415            cpu,
416            memory: memory(),
417            gpu: None,
418        }
419    }
420}
421
422/// The CPU time (user and system) the process used so far.
423#[cfg(unix)]
424fn cpu_time() -> Option<Duration> {
425    let mut usage = std::mem::MaybeUninit::<libc::rusage>::uninit();
426    // SAFETY: `usage` is a buffer of the layout the call fills.
427    if unsafe { libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) } != 0 {
428        return None;
429    }
430    // SAFETY: a zero return means the call filled the buffer.
431    let usage = unsafe { usage.assume_init() };
432    let time = |t: libc::timeval| Duration::new(t.tv_sec as u64, t.tv_usec as u32 * 1000);
433    Some(time(usage.ru_utime) + time(usage.ru_stime))
434}
435
436#[cfg(not(unix))]
437fn cpu_time() -> Option<Duration> {
438    None
439}
440
441/// The physical footprint (`proc_pid_rusage`): the dirty and compressed
442/// memory the process owns, what Activity Monitor shows and what the system
443/// judges it by under memory pressure (unlike the resident size, it leaves
444/// out the frameworks' clean pages every process maps).
445#[cfg(target_vendor = "apple")]
446fn memory() -> Option<u64> {
447    unsafe extern "C" {
448        // libSystem's (libproc) on every Apple platform; the `libc` crate
449        // declares it for macOS only.
450        fn proc_pid_rusage(
451            pid: libc::c_int,
452            flavor: libc::c_int,
453            buffer: *mut libc::rusage_info_t,
454        ) -> libc::c_int;
455    }
456    let mut info = std::mem::MaybeUninit::<libc::rusage_info_v2>::uninit();
457    // SAFETY: `info` is a buffer of exactly the layout `RUSAGE_INFO_V2`
458    // names, the only thing the call writes.
459    let status = unsafe {
460        proc_pid_rusage(
461            std::process::id() as libc::c_int,
462            libc::RUSAGE_INFO_V2,
463            info.as_mut_ptr().cast::<libc::rusage_info_t>(),
464        )
465    };
466    // SAFETY: a zero return means the call filled the buffer.
467    (status == 0).then(|| unsafe { info.assume_init() }.ri_phys_footprint)
468}
469
470/// The resident set (`/proc/self/statm`'s second field, in pages).
471#[cfg(any(target_os = "linux", target_os = "android"))]
472fn memory() -> Option<u64> {
473    let statm = std::fs::read_to_string("/proc/self/statm").ok()?;
474    let pages: u64 = statm.split_whitespace().nth(1)?.parse().ok()?;
475    // SAFETY: a plain query of the page size.
476    let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
477    Some(pages * u64::try_from(page).ok()?)
478}
479
480#[cfg(not(any(target_vendor = "apple", target_os = "linux", target_os = "android")))]
481fn memory() -> Option<u64> {
482    None
483}
484
485#[cfg(test)]
486mod tests {
487    use super::*;
488
489    fn ms(ms: u64) -> Duration {
490        Duration::from_millis(ms)
491    }
492
493    #[test]
494    fn stat_of_samples() {
495        let stat = Stat::of((1..=20).map(ms));
496        assert_eq!(stat.mean, Duration::from_micros(10_500));
497        assert_eq!(stat.p50, ms(10));
498        assert_eq!(stat.p95, ms(19));
499        assert_eq!(stat.max, ms(20));
500        assert_eq!(Stat::of(std::iter::empty()), Stat::default());
501    }
502
503    #[test]
504    fn frames_are_refreshes_that_changed_something() {
505        let monitor = PerfMonitor::new();
506        let start = Instant::now();
507        let period = Duration::from_micros(8333);
508        for i in 0..(WARMUP + 10) {
509            monitor.record_work(ms(1), true);
510            // Work that changed nothing is part of the next frame's cost.
511            monitor.record_work(ms(1), false);
512            monitor.vsync(start + period * i, period);
513            // A refresh with nothing new is not a frame.
514            monitor.vsync(start + period * i + period / 2, period);
515        }
516        let snapshot = monitor.snapshot();
517        assert_eq!(snapshot.frames.len(), 10);
518        assert_eq!(snapshot.frame.mean, ms(2));
519        assert!((snapshot.refresh_rate.unwrap() - 120.0).abs() < 0.5);
520        // 2ms frames could run at 500 per second, but not on a 120 Hz display.
521        assert!((snapshot.max_fps - 120.0).abs() < 0.5);
522        assert_eq!(snapshot.dropped, 0.0);
523    }
524
525    #[test]
526    fn slow_frames_are_dropped_ones() {
527        let monitor = PerfMonitor::new();
528        let start = Instant::now();
529        let period = ms(16);
530        for i in 0..(WARMUP + 4) {
531            monitor.record_work(if i % 2 == 0 { ms(20) } else { ms(1) }, true);
532            monitor.vsync(start + period * i, period);
533        }
534        assert_eq!(monitor.snapshot().dropped, 0.5);
535    }
536
537    #[test]
538    fn commits_after_warmup() {
539        let monitor = PerfMonitor::new();
540        for _ in 0..(WARMUP + 3) {
541            monitor.record_commit(CommitTiming {
542                js: ms(1),
543                layout: ms(2),
544                ops: 3,
545                items: 4,
546            });
547        }
548        let snapshot = monitor.snapshot();
549        assert_eq!(snapshot.commits, 3.0);
550        assert_eq!(snapshot.js.mean, ms(1));
551        assert_eq!(snapshot.layout.p95, ms(2));
552        assert_eq!(snapshot.items, 4.0);
553    }
554
555    #[test]
556    fn process_sample_reads_memory() {
557        let mut sampler = ProcessSampler::new();
558        let first = sampler.sample();
559        assert_eq!(first.cpu, None);
560        #[cfg(any(target_vendor = "apple", target_os = "linux"))]
561        assert!(first.memory.is_some_and(|m| m > 0));
562        std::thread::sleep(ms(5));
563        #[cfg(unix)]
564        assert!(sampler.sample().cpu.is_some());
565    }
566}