1use std::{collections::VecDeque, sync::Mutex, time::Duration};
32
33pub const ENV_VAR: &str = "NSH_FPS";
37
38pub 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
46pub const LOG_TARGET: &str = "nsh::fps";
51
52use nsh_core::time::Instant;
53
54const CAPACITY: usize = 120;
56
57const RATE_WINDOW: Duration = Duration::from_secs(1);
59
60const WARMUP: u32 = 4;
64
65#[derive(Debug, Clone, Copy, Default, PartialEq)]
67pub struct CommitTiming {
68 pub js: Duration,
72 pub layout: Duration,
75 pub ops: u32,
77 pub items: u32,
79}
80
81#[derive(Debug, Clone, Copy, Default, PartialEq)]
83pub struct Stat {
84 pub mean: Duration,
86 pub p50: Duration,
88 pub p95: Duration,
90 pub max: Duration,
92}
93
94impl Stat {
95 fn of(samples: impl Iterator<Item = Duration>) -> Stat {
96 let mut sorted: Vec<Duration> = samples.collect();
97 if sorted.is_empty() {
98 return Stat::default();
99 }
100 sorted.sort_unstable();
101 let sum: Duration = sorted.iter().sum();
102 let at = |q: f32| ((sorted.len() as f32 * q).ceil() as usize).clamp(1, sorted.len()) - 1;
103 let p95 = at(0.95);
104 Stat {
105 mean: sum / sorted.len() as u32,
106 p50: sorted[at(0.5)],
107 p95: sorted[p95],
108 max: sorted[sorted.len() - 1],
109 }
110 }
111}
112
113#[derive(Debug, Clone, Copy, Default, PartialEq)]
115pub struct ProcessSample {
116 pub cpu: Option<f32>,
120 pub memory: Option<u64>,
124 pub gpu: Option<f32>,
127}
128
129#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
132pub struct MemorySample {
133 pub js_heap: u64,
135 pub js_objects: u64,
137 pub nodes: u64,
139 pub node_ids: u64,
142}
143
144#[derive(Debug, Clone, Default, PartialEq)]
146pub struct PerfSnapshot {
147 pub fps: f32,
151 pub max_fps: f32,
154 pub refresh_rate: Option<f32>,
156 pub tick_interval: Stat,
160 pub frame_interval: Stat,
163 pub frame: Stat,
166 pub dropped: f32,
168 pub commits: f32,
170 pub js: Stat,
172 pub layout: Stat,
174 pub items: f32,
176 pub latency: Stat,
179 pub engine_busy: f32,
181 pub frames: Vec<Duration>,
183 pub process: ProcessSample,
185 pub memory: Option<MemorySample>,
188}
189
190#[derive(Debug)]
193pub struct PerfMonitor {
194 inner: Mutex<Inner>,
195}
196
197#[derive(Debug)]
198struct Inner {
199 pending: Duration,
202 dirty: bool,
203 frames: VecDeque<(Instant, Duration)>,
205 frame_warmup: u32,
206 refresh: Option<f32>,
207 last_vsync: Option<Instant>,
210 ticks: VecDeque<Duration>,
211 commits: VecDeque<(Instant, CommitTiming)>,
212 commit_warmup: u32,
213 latencies: VecDeque<Duration>,
214 busy: VecDeque<(Instant, Duration)>,
216 process: ProcessSample,
217 memory: Option<MemorySample>,
218}
219
220impl Default for PerfMonitor {
221 fn default() -> Self {
222 PerfMonitor {
223 inner: Mutex::new(Inner {
224 pending: Duration::ZERO,
225 dirty: false,
226 frames: VecDeque::with_capacity(CAPACITY),
227 frame_warmup: WARMUP,
228 refresh: None,
229 last_vsync: None,
230 ticks: VecDeque::with_capacity(CAPACITY),
231 commits: VecDeque::with_capacity(CAPACITY),
232 commit_warmup: WARMUP,
233 latencies: VecDeque::with_capacity(CAPACITY),
234 busy: VecDeque::new(),
235 process: ProcessSample::default(),
236 memory: None,
237 }),
238 }
239 }
240}
241
242fn push<T>(queue: &mut VecDeque<T>, value: T) {
243 if queue.len() == CAPACITY {
244 queue.pop_front();
245 }
246 queue.push_back(value);
247}
248
249impl PerfMonitor {
250 pub fn new() -> PerfMonitor {
252 PerfMonitor::default()
253 }
254
255 fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
256 self.inner.lock().unwrap_or_else(|e| e.into_inner())
257 }
258
259 pub fn record_work(&self, cost: Duration, dirty: bool) {
263 let mut inner = self.lock();
264 inner.pending += cost;
265 inner.dirty |= dirty;
266 }
267
268 pub fn vsync(&self, at: Instant, interval: Duration) {
272 let mut inner = self.lock();
273 if interval > Duration::ZERO {
274 let rate = 1.0 / interval.as_secs_f32();
275 inner.refresh = Some(match inner.refresh {
277 Some(r) if (r - rate).abs() < r * 0.1 => r + (rate - r) * 0.1,
278 _ => rate,
279 });
280 }
281 if let Some(last) = inner.last_vsync.replace(at) {
282 let gap = at.duration_since(last);
283 if gap < Duration::from_millis(100) {
286 push(&mut inner.ticks, gap);
287 }
288 }
289 let cost = std::mem::take(&mut inner.pending);
290 if !std::mem::take(&mut inner.dirty) {
291 return;
292 }
293 if inner.frame_warmup > 0 {
294 inner.frame_warmup -= 1;
295 return;
296 }
297 push(&mut inner.frames, (at, cost));
298 }
299
300 pub fn record_latency(&self, latency: Duration) {
303 let mut inner = self.lock();
304 if inner.frame_warmup == 0 {
306 push(&mut inner.latencies, latency);
307 }
308 }
309
310 pub fn record_commit(&self, timing: CommitTiming) {
312 let mut inner = self.lock();
313 if inner.commit_warmup > 0 {
314 inner.commit_warmup -= 1;
315 return;
316 }
317 push(&mut inner.commits, (Instant::now(), timing));
318 }
319
320 pub fn record_busy(&self, busy: Duration) {
322 let now = Instant::now();
323 let mut inner = self.lock();
324 inner.busy.push_back((now, busy));
325 while inner
326 .busy
327 .front()
328 .is_some_and(|&(at, _)| now.duration_since(at) > RATE_WINDOW)
329 {
330 inner.busy.pop_front();
331 }
332 }
333
334 pub fn set_process(&self, sample: ProcessSample) {
337 self.lock().process = sample;
338 }
339
340 pub fn set_memory(&self, sample: MemorySample) {
342 self.lock().memory = Some(sample);
343 }
344
345 pub fn snapshot(&self) -> PerfSnapshot {
347 let now = Instant::now();
348 let inner = self.lock();
349 let recent = |at: Instant| now.duration_since(at) <= RATE_WINDOW;
350 let shown: Vec<Instant> = inner
353 .frames
354 .iter()
355 .map(|&(at, _)| at)
356 .filter(|&at| recent(at))
357 .collect();
358 let fps = match (shown.first(), shown.last()) {
359 (Some(&first), Some(&last)) if shown.len() >= 2 && last > first => {
360 let span = now.duration_since(first).max(last.duration_since(first));
363 (shown.len() - 1) as f32 / span.as_secs_f32()
364 }
365 _ => 0.0,
366 };
367 let frame = Stat::of(inner.frames.iter().map(|&(_, cost)| cost));
368 let budget = Duration::from_secs_f32(1.0 / inner.refresh.unwrap_or(60.0));
369 let dropped = match inner.frames.len() {
370 0 => 0.0,
371 n => {
372 inner
373 .frames
374 .iter()
375 .filter(|&&(_, cost)| cost > budget)
376 .count() as f32
377 / n as f32
378 }
379 };
380 let max_fps = if frame.mean > Duration::ZERO {
381 let max = 1.0 / frame.mean.as_secs_f32();
382 inner.refresh.map_or(max, |r| max.min(r))
383 } else {
384 0.0
385 };
386 let commits = inner.commits.iter().filter(|&&(at, _)| recent(at)).count() as f32;
387 let items = match inner.commits.len() {
388 0 => 0.0,
389 n => {
390 inner
391 .commits
392 .iter()
393 .map(|(_, c)| c.items as f32)
394 .sum::<f32>()
395 / n as f32
396 }
397 };
398 let busy: Duration = inner
399 .busy
400 .iter()
401 .filter(|&&(at, _)| recent(at))
402 .map(|&(_, d)| d)
403 .sum();
404 PerfSnapshot {
405 fps,
406 max_fps,
407 refresh_rate: inner.refresh,
408 tick_interval: Stat::of(inner.ticks.iter().copied()),
409 frame_interval: Stat::of(
410 inner
411 .frames
412 .iter()
413 .zip(inner.frames.iter().skip(1))
414 .map(|(&(a, _), &(b, _))| b.duration_since(a)),
415 ),
416 frame,
417 dropped,
418 commits,
419 js: Stat::of(inner.commits.iter().map(|(_, c)| c.js)),
420 layout: Stat::of(inner.commits.iter().map(|(_, c)| c.layout)),
421 items,
422 latency: Stat::of(inner.latencies.iter().copied()),
423 engine_busy: busy.as_secs_f32() / RATE_WINDOW.as_secs_f32() * 100.0,
424 frames: inner.frames.iter().map(|&(_, cost)| cost).collect(),
425 process: inner.process,
426 memory: inner.memory,
427 }
428 }
429}
430
431pub const CPU_WINDOW: Duration = Duration::from_secs(1);
437
438const CPU_MIN_SPAN: Duration = Duration::from_millis(250);
441
442#[derive(Debug)]
447pub struct ProcessSampler {
448 readings: VecDeque<(Duration, Instant)>,
451}
452
453impl Default for ProcessSampler {
454 fn default() -> Self {
455 ProcessSampler::new()
456 }
457}
458
459impl ProcessSampler {
460 pub fn new() -> ProcessSampler {
462 ProcessSampler {
463 readings: VecDeque::new(),
464 }
465 }
466
467 pub fn sample(&mut self) -> ProcessSample {
470 let now = Instant::now();
471 ProcessSample {
472 cpu: cpu_time().and_then(|used| self.rate(used, now)),
473 memory: memory(),
474 gpu: None,
475 }
476 }
477
478 fn rate(&mut self, used: Duration, now: Instant) -> Option<f32> {
481 self.readings.push_back((used, now));
482 while self
483 .readings
484 .get(1)
485 .is_some_and(|(_, at)| now.duration_since(*at) >= CPU_WINDOW)
486 {
487 self.readings.pop_front();
488 }
489 let (base, at) = *self.readings.front()?;
490 let span = now.duration_since(at);
491 (span >= CPU_MIN_SPAN)
492 .then(|| used.saturating_sub(base).as_secs_f32() / span.as_secs_f32() * 100.0)
493 }
494}
495
496#[cfg(unix)]
498fn cpu_time() -> Option<Duration> {
499 let mut usage = std::mem::MaybeUninit::<libc::rusage>::uninit();
500 if unsafe { libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) } != 0 {
502 return None;
503 }
504 let usage = unsafe { usage.assume_init() };
506 let time = |t: libc::timeval| Duration::new(t.tv_sec as u64, t.tv_usec as u32 * 1000);
507 Some(time(usage.ru_utime) + time(usage.ru_stime))
508}
509
510#[cfg(windows)]
511fn cpu_time() -> Option<Duration> {
512 use windows_sys::Win32::{
513 Foundation::FILETIME,
514 System::Threading::{GetCurrentProcess, GetProcessTimes},
515 };
516 let zero = FILETIME {
517 dwLowDateTime: 0,
518 dwHighDateTime: 0,
519 };
520 let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero);
521 let ok = unsafe {
523 GetProcessTimes(
524 GetCurrentProcess(),
525 &mut created,
526 &mut exited,
527 &mut kernel,
528 &mut user,
529 )
530 };
531 let ticks = |t: FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime);
533 (ok != 0).then(|| Duration::from_nanos((ticks(kernel) + ticks(user)) * 100))
534}
535
536#[cfg(not(any(unix, windows)))]
537fn cpu_time() -> Option<Duration> {
538 None
539}
540
541#[cfg(target_vendor = "apple")]
549fn memory() -> Option<u64> {
550 #[repr(C)]
554 struct TaskVmInfo {
555 before: [u64; 18],
558 phys_footprint: u64,
559 }
560 unsafe extern "C" {
561 static mach_task_self_: libc::mach_port_t;
564 }
565 const TASK_VM_INFO: libc::task_flavor_t = 22;
566 const _: () = assert!(std::mem::size_of::<TaskVmInfo>() == 152);
567 let words = std::mem::size_of::<TaskVmInfo>() / std::mem::size_of::<libc::natural_t>();
568 let mut count = words as libc::mach_msg_type_number_t;
569 let mut info = std::mem::MaybeUninit::<TaskVmInfo>::uninit();
570 let status = unsafe {
574 libc::task_info(
575 mach_task_self_,
576 TASK_VM_INFO,
577 info.as_mut_ptr().cast::<libc::integer_t>(),
578 &mut count,
579 )
580 };
581 (status == libc::KERN_SUCCESS && count as usize == words)
583 .then(|| unsafe { info.assume_init() }.phys_footprint)
584}
585
586#[cfg(any(target_os = "linux", target_os = "android"))]
588fn memory() -> Option<u64> {
589 let statm = std::fs::read_to_string("/proc/self/statm").ok()?;
590 let pages: u64 = statm.split_whitespace().nth(1)?.parse().ok()?;
591 let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
593 Some(pages * u64::try_from(page).ok()?)
594}
595
596#[cfg(windows)]
598fn memory() -> Option<u64> {
599 use windows_sys::Win32::System::{
600 ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS},
601 Threading::GetCurrentProcess,
602 };
603 let mut counters: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() };
605 counters.cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
606 let ok = unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) };
608 (ok != 0).then_some(counters.WorkingSetSize as u64)
609}
610
611#[cfg(not(any(
612 target_vendor = "apple",
613 target_os = "linux",
614 target_os = "android",
615 windows
616)))]
617fn memory() -> Option<u64> {
618 None
619}
620
621#[cfg(test)]
622mod tests {
623 use super::*;
624
625 fn ms(ms: u64) -> Duration {
626 Duration::from_millis(ms)
627 }
628
629 #[test]
630 fn stat_of_samples() {
631 let stat = Stat::of((1..=20).map(ms));
632 assert_eq!(stat.mean, Duration::from_micros(10_500));
633 assert_eq!(stat.p50, ms(10));
634 assert_eq!(stat.p95, ms(19));
635 assert_eq!(stat.max, ms(20));
636 assert_eq!(Stat::of(std::iter::empty()), Stat::default());
637 }
638
639 #[test]
640 fn frames_are_refreshes_that_changed_something() {
641 let monitor = PerfMonitor::new();
642 let start = Instant::now();
643 let period = Duration::from_micros(8333);
644 for i in 0..(WARMUP + 10) {
645 monitor.record_work(ms(1), true);
646 monitor.record_work(ms(1), false);
648 monitor.vsync(start + period * i, period);
649 monitor.vsync(start + period * i + period / 2, period);
651 }
652 let snapshot = monitor.snapshot();
653 assert_eq!(snapshot.frames.len(), 10);
654 assert_eq!(snapshot.frame.mean, ms(2));
655 assert!((snapshot.refresh_rate.unwrap() - 120.0).abs() < 0.5);
656 assert!((snapshot.max_fps - 120.0).abs() < 0.5);
658 assert_eq!(snapshot.dropped, 0.0);
659 }
660
661 #[test]
662 fn slow_frames_are_dropped_ones() {
663 let monitor = PerfMonitor::new();
664 let start = Instant::now();
665 let period = ms(16);
666 for i in 0..(WARMUP + 4) {
667 monitor.record_work(if i % 2 == 0 { ms(20) } else { ms(1) }, true);
668 monitor.vsync(start + period * i, period);
669 }
670 assert_eq!(monitor.snapshot().dropped, 0.5);
671 }
672
673 #[test]
674 fn commits_after_warmup() {
675 let monitor = PerfMonitor::new();
676 for _ in 0..(WARMUP + 3) {
677 monitor.record_commit(CommitTiming {
678 js: ms(1),
679 layout: ms(2),
680 ops: 3,
681 items: 4,
682 });
683 }
684 let snapshot = monitor.snapshot();
685 assert_eq!(snapshot.commits, 3.0);
686 assert_eq!(snapshot.js.mean, ms(1));
687 assert_eq!(snapshot.layout.p95, ms(2));
688 assert_eq!(snapshot.items, 4.0);
689 }
690
691 #[test]
692 fn process_sample_reads_memory() {
693 let mut sampler = ProcessSampler::new();
694 let first = sampler.sample();
695 assert_eq!(first.cpu, None);
696 #[cfg(any(target_vendor = "apple", target_os = "linux"))]
697 assert!(first.memory.is_some_and(|m| m > 0));
698 std::thread::sleep(CPU_MIN_SPAN);
699 #[cfg(unix)]
700 assert!(sampler.sample().cpu.is_some());
701 }
702
703 #[test]
707 fn cpu_is_a_rate_over_the_window() {
708 let mut sampler = ProcessSampler::new();
709 let start = Instant::now();
710 let at = |ms: u64| start + Duration::from_millis(ms);
711 let near = |rate: Option<f32>, expected: f64| {
712 rate.is_some_and(|r| (r as f64 - expected).abs() < 0.01)
713 };
714 assert_eq!(sampler.rate(ms(0), at(0)), None);
715 assert_eq!(sampler.rate(ms(5), at(10)), None);
717 assert!(near(sampler.rate(ms(50), at(500)), 10.0));
718 assert!(near(sampler.rate(ms(100), at(1000)), 10.0));
721 assert!(near(
722 sampler.rate(ms(104), at(1004)),
723 104.0 / 1004.0 * 100.0
724 ));
725 sampler.rate(ms(1100), at(2000));
727 assert!(near(sampler.rate(ms(2100), at(3000)), 100.0));
728 }
729
730 #[cfg(target_os = "macos")]
734 #[test]
735 fn footprint_matches_proc_pid_rusage() {
736 let ours = super::memory().expect("task_info");
737 let mut info = std::mem::MaybeUninit::<libc::rusage_info_v2>::uninit();
738 let status = unsafe {
741 libc::proc_pid_rusage(
742 std::process::id() as libc::c_int,
743 libc::RUSAGE_INFO_V2,
744 info.as_mut_ptr().cast::<libc::rusage_info_t>(),
745 )
746 };
747 assert_eq!(status, 0);
748 let theirs = unsafe { info.assume_init() }.ri_phys_footprint;
750 assert!(ours.abs_diff(theirs) < 8 << 20, "{ours} vs {theirs}");
751 }
752}