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 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
57pub const LOG_TARGET: &str = "nsh::fps";
62
63pub const STARTUP_LOG_TARGET: &str = "nsh::startup";
65
66pub 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
80fn since_process_start() -> Option<f64> {
83 #[cfg(target_os = "linux")]
84 {
85 let stat = std::fs::read_to_string("/proc/self/stat").ok()?;
86 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
99const CAPACITY: usize = 120;
101
102const RATE_WINDOW: Duration = Duration::from_secs(1);
104
105const WARMUP: u32 = 4;
109
110#[derive(Debug, Clone, Copy, Default, PartialEq)]
112pub struct CommitTiming {
113 pub js: Duration,
117 pub layout: Duration,
120 pub ops: u32,
122 pub items: u32,
124}
125
126#[derive(Debug, Clone, Copy, Default, PartialEq)]
128pub struct Stat {
129 pub mean: Duration,
131 pub p50: Duration,
133 pub p95: Duration,
135 pub max: Duration,
137}
138
139impl Stat {
140 fn of(samples: impl Iterator<Item = Duration>) -> Stat {
141 let mut sorted: Vec<Duration> = samples.collect();
142 if sorted.is_empty() {
143 return Stat::default();
144 }
145 sorted.sort_unstable();
146 let sum: Duration = sorted.iter().sum();
147 let at = |q: f32| ((sorted.len() as f32 * q).ceil() as usize).clamp(1, sorted.len()) - 1;
148 let p95 = at(0.95);
149 Stat {
150 mean: sum / sorted.len() as u32,
151 p50: sorted[at(0.5)],
152 p95: sorted[p95],
153 max: sorted[sorted.len() - 1],
154 }
155 }
156}
157
158#[derive(Debug, Clone, Copy, Default, PartialEq)]
160pub struct ProcessSample {
161 pub cpu: Option<f32>,
165 pub memory: Option<u64>,
169 pub gpu: Option<f32>,
172}
173
174#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
177pub struct MemorySample {
178 pub js_heap: u64,
180 pub js_objects: u64,
182 pub nodes: u64,
184 pub node_ids: u64,
187}
188
189#[derive(Debug, Clone, Default, PartialEq)]
191pub struct PerfSnapshot {
192 pub fps: f32,
196 pub max_fps: f32,
199 pub refresh_rate: Option<f32>,
201 pub tick_interval: Stat,
205 pub frame_interval: Stat,
208 pub frame: Stat,
211 pub dropped: f32,
213 pub commits: f32,
215 pub js: Stat,
217 pub layout: Stat,
219 pub items: f32,
221 pub latency: Stat,
224 pub engine_busy: f32,
226 pub frames: Vec<Duration>,
228 pub process: ProcessSample,
230 pub memory: Option<MemorySample>,
233}
234
235impl PerfSnapshot {
236 pub fn stats(&self) -> nsh_core::platform::PerfStats {
238 let mut stats = nsh_core::platform::PerfStats::new(self.fps);
239 stats.refresh_rate = self.refresh_rate;
240 stats.dropped = nsh_core::geometry::Percentage(self.dropped);
241 stats
242 }
243}
244
245#[derive(Debug)]
248pub struct PerfMonitor {
249 inner: Mutex<Inner>,
250}
251
252#[derive(Debug)]
253struct Inner {
254 pending: Duration,
257 dirty: bool,
258 frames: VecDeque<(Instant, Duration)>,
260 frame_warmup: u32,
261 refresh: Option<f32>,
262 last_vsync: Option<Instant>,
265 ticks: VecDeque<Duration>,
266 commits: VecDeque<(Instant, CommitTiming)>,
267 commit_warmup: u32,
268 latencies: VecDeque<Duration>,
269 busy: VecDeque<(Instant, Duration)>,
271 process: ProcessSample,
272 memory: Option<MemorySample>,
273}
274
275impl Default for PerfMonitor {
276 fn default() -> Self {
277 PerfMonitor {
278 inner: Mutex::new(Inner {
279 pending: Duration::ZERO,
280 dirty: false,
281 frames: VecDeque::with_capacity(CAPACITY),
282 frame_warmup: WARMUP,
283 refresh: None,
284 last_vsync: None,
285 ticks: VecDeque::with_capacity(CAPACITY),
286 commits: VecDeque::with_capacity(CAPACITY),
287 commit_warmup: WARMUP,
288 latencies: VecDeque::with_capacity(CAPACITY),
289 busy: VecDeque::new(),
290 process: ProcessSample::default(),
291 memory: None,
292 }),
293 }
294 }
295}
296
297fn push<T>(queue: &mut VecDeque<T>, value: T) {
298 if queue.len() == CAPACITY {
299 queue.pop_front();
300 }
301 queue.push_back(value);
302}
303
304impl PerfMonitor {
305 pub fn new() -> PerfMonitor {
307 PerfMonitor::default()
308 }
309
310 fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
311 self.inner.lock().unwrap_or_else(|e| e.into_inner())
312 }
313
314 pub fn record_work(&self, cost: Duration, dirty: bool) {
318 let mut inner = self.lock();
319 inner.pending += cost;
320 inner.dirty |= dirty;
321 }
322
323 pub fn vsync(&self, at: Instant, interval: Duration) {
327 let mut inner = self.lock();
328 if interval > Duration::ZERO {
329 let rate = 1.0 / interval.as_secs_f32();
330 inner.refresh = Some(match inner.refresh {
332 Some(r) if (r - rate).abs() < r * 0.1 => r + (rate - r) * 0.1,
333 _ => rate,
334 });
335 }
336 if let Some(last) = inner.last_vsync.replace(at) {
337 let gap = at.duration_since(last);
338 if gap < Duration::from_millis(100) {
341 push(&mut inner.ticks, gap);
342 }
343 }
344 let cost = std::mem::take(&mut inner.pending);
345 if !std::mem::take(&mut inner.dirty) {
346 return;
347 }
348 if inner.frame_warmup > 0 {
349 inner.frame_warmup -= 1;
350 return;
351 }
352 push(&mut inner.frames, (at, cost));
353 }
354
355 pub fn record_latency(&self, latency: Duration) {
358 let mut inner = self.lock();
359 if inner.frame_warmup == 0 {
361 push(&mut inner.latencies, latency);
362 }
363 }
364
365 pub fn record_commit(&self, timing: CommitTiming) {
367 let mut inner = self.lock();
368 if inner.commit_warmup > 0 {
369 inner.commit_warmup -= 1;
370 return;
371 }
372 push(&mut inner.commits, (Instant::now(), timing));
373 }
374
375 pub fn record_busy(&self, busy: Duration) {
377 let now = Instant::now();
378 let mut inner = self.lock();
379 inner.busy.push_back((now, busy));
380 while inner
381 .busy
382 .front()
383 .is_some_and(|&(at, _)| now.duration_since(at) > RATE_WINDOW)
384 {
385 inner.busy.pop_front();
386 }
387 }
388
389 pub fn set_process(&self, sample: ProcessSample) {
392 self.lock().process = sample;
393 }
394
395 pub fn set_memory(&self, sample: MemorySample) {
397 self.lock().memory = Some(sample);
398 }
399
400 pub fn snapshot(&self) -> PerfSnapshot {
402 let now = Instant::now();
403 let inner = self.lock();
404 let recent = |at: Instant| now.duration_since(at) <= RATE_WINDOW;
405 let shown: Vec<Instant> = inner
408 .frames
409 .iter()
410 .map(|&(at, _)| at)
411 .filter(|&at| recent(at))
412 .collect();
413 let fps = match (shown.first(), shown.last()) {
414 (Some(&first), Some(&last)) if shown.len() >= 2 && last > first => {
415 let span = now.duration_since(first).max(last.duration_since(first));
418 (shown.len() - 1) as f32 / span.as_secs_f32()
419 }
420 _ => 0.0,
421 };
422 let frame = Stat::of(inner.frames.iter().map(|&(_, cost)| cost));
423 let budget = Duration::from_secs_f32(1.0 / inner.refresh.unwrap_or(60.0));
424 let dropped = match inner.frames.len() {
425 0 => 0.0,
426 n => {
427 inner
428 .frames
429 .iter()
430 .filter(|&&(_, cost)| cost > budget)
431 .count() as f32
432 / n as f32
433 }
434 };
435 let max_fps = if frame.mean > Duration::ZERO {
436 let max = 1.0 / frame.mean.as_secs_f32();
437 inner.refresh.map_or(max, |r| max.min(r))
438 } else {
439 0.0
440 };
441 let commits = inner.commits.iter().filter(|&&(at, _)| recent(at)).count() as f32;
442 let items = match inner.commits.len() {
443 0 => 0.0,
444 n => {
445 inner
446 .commits
447 .iter()
448 .map(|(_, c)| c.items as f32)
449 .sum::<f32>()
450 / n as f32
451 }
452 };
453 let busy: Duration = inner
454 .busy
455 .iter()
456 .filter(|&&(at, _)| recent(at))
457 .map(|&(_, d)| d)
458 .sum();
459 PerfSnapshot {
460 fps,
461 max_fps,
462 refresh_rate: inner.refresh,
463 tick_interval: Stat::of(inner.ticks.iter().copied()),
464 frame_interval: Stat::of(
465 inner
466 .frames
467 .iter()
468 .zip(inner.frames.iter().skip(1))
469 .map(|(&(a, _), &(b, _))| b.duration_since(a)),
470 ),
471 frame,
472 dropped,
473 commits,
474 js: Stat::of(inner.commits.iter().map(|(_, c)| c.js)),
475 layout: Stat::of(inner.commits.iter().map(|(_, c)| c.layout)),
476 items,
477 latency: Stat::of(inner.latencies.iter().copied()),
478 engine_busy: busy.as_secs_f32() / RATE_WINDOW.as_secs_f32() * 100.0,
479 frames: inner.frames.iter().map(|&(_, cost)| cost).collect(),
480 process: inner.process,
481 memory: inner.memory,
482 }
483 }
484}
485
486pub const CPU_WINDOW: Duration = Duration::from_secs(1);
492
493const CPU_MIN_SPAN: Duration = Duration::from_millis(250);
496
497#[derive(Debug)]
502pub struct ProcessSampler {
503 readings: VecDeque<(Duration, Instant)>,
506}
507
508impl Default for ProcessSampler {
509 fn default() -> Self {
510 ProcessSampler::new()
511 }
512}
513
514impl ProcessSampler {
515 pub fn new() -> ProcessSampler {
517 ProcessSampler {
518 readings: VecDeque::new(),
519 }
520 }
521
522 pub fn sample(&mut self) -> ProcessSample {
525 let now = Instant::now();
526 ProcessSample {
527 cpu: cpu_time().and_then(|used| self.rate(used, now)),
528 memory: memory(),
529 gpu: None,
530 }
531 }
532
533 fn rate(&mut self, used: Duration, now: Instant) -> Option<f32> {
536 self.readings.push_back((used, now));
537 while self
538 .readings
539 .get(1)
540 .is_some_and(|(_, at)| now.duration_since(*at) >= CPU_WINDOW)
541 {
542 self.readings.pop_front();
543 }
544 let (base, at) = *self.readings.front()?;
545 let span = now.duration_since(at);
546 (span >= CPU_MIN_SPAN)
547 .then(|| used.saturating_sub(base).as_secs_f32() / span.as_secs_f32() * 100.0)
548 }
549}
550
551#[cfg(unix)]
553fn cpu_time() -> Option<Duration> {
554 let mut usage = std::mem::MaybeUninit::<libc::rusage>::uninit();
555 if unsafe { libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) } != 0 {
557 return None;
558 }
559 let usage = unsafe { usage.assume_init() };
561 let time = |t: libc::timeval| Duration::new(t.tv_sec as u64, t.tv_usec as u32 * 1000);
562 Some(time(usage.ru_utime) + time(usage.ru_stime))
563}
564
565#[cfg(windows)]
566fn cpu_time() -> Option<Duration> {
567 use windows_sys::Win32::{
568 Foundation::FILETIME,
569 System::Threading::{GetCurrentProcess, GetProcessTimes},
570 };
571 let zero = FILETIME {
572 dwLowDateTime: 0,
573 dwHighDateTime: 0,
574 };
575 let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero);
576 let ok = unsafe {
578 GetProcessTimes(
579 GetCurrentProcess(),
580 &mut created,
581 &mut exited,
582 &mut kernel,
583 &mut user,
584 )
585 };
586 let ticks = |t: FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime);
588 (ok != 0).then(|| Duration::from_nanos((ticks(kernel) + ticks(user)) * 100))
589}
590
591#[cfg(not(any(unix, windows)))]
592fn cpu_time() -> Option<Duration> {
593 None
594}
595
596#[cfg(target_vendor = "apple")]
604fn memory() -> Option<u64> {
605 #[repr(C)]
609 struct TaskVmInfo {
610 before: [u64; 18],
613 phys_footprint: u64,
614 }
615 unsafe extern "C" {
616 static mach_task_self_: libc::mach_port_t;
619 }
620 const TASK_VM_INFO: libc::task_flavor_t = 22;
621 const _: () = assert!(std::mem::size_of::<TaskVmInfo>() == 152);
622 let words = std::mem::size_of::<TaskVmInfo>() / std::mem::size_of::<libc::natural_t>();
623 let mut count = words as libc::mach_msg_type_number_t;
624 let mut info = std::mem::MaybeUninit::<TaskVmInfo>::uninit();
625 let status = unsafe {
629 libc::task_info(
630 mach_task_self_,
631 TASK_VM_INFO,
632 info.as_mut_ptr().cast::<libc::integer_t>(),
633 &mut count,
634 )
635 };
636 (status == libc::KERN_SUCCESS && count as usize == words)
638 .then(|| unsafe { info.assume_init() }.phys_footprint)
639}
640
641#[cfg(any(target_os = "linux", target_os = "android"))]
643fn memory() -> Option<u64> {
644 let statm = std::fs::read_to_string("/proc/self/statm").ok()?;
645 let pages: u64 = statm.split_whitespace().nth(1)?.parse().ok()?;
646 let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
648 Some(pages * u64::try_from(page).ok()?)
649}
650
651#[cfg(windows)]
653fn memory() -> Option<u64> {
654 use windows_sys::Win32::System::{
655 ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS},
656 Threading::GetCurrentProcess,
657 };
658 let mut counters: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() };
660 counters.cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
661 let ok = unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) };
663 (ok != 0).then_some(counters.WorkingSetSize as u64)
664}
665
666#[cfg(not(any(
667 target_vendor = "apple",
668 target_os = "linux",
669 target_os = "android",
670 windows
671)))]
672fn memory() -> Option<u64> {
673 None
674}
675
676#[cfg(test)]
677mod tests {
678 use super::*;
679
680 fn ms(ms: u64) -> Duration {
681 Duration::from_millis(ms)
682 }
683
684 #[test]
685 fn stat_of_samples() {
686 let stat = Stat::of((1..=20).map(ms));
687 assert_eq!(stat.mean, Duration::from_micros(10_500));
688 assert_eq!(stat.p50, ms(10));
689 assert_eq!(stat.p95, ms(19));
690 assert_eq!(stat.max, ms(20));
691 assert_eq!(Stat::of(std::iter::empty()), Stat::default());
692 }
693
694 #[test]
695 fn frames_are_refreshes_that_changed_something() {
696 let monitor = PerfMonitor::new();
697 let start = Instant::now();
698 let period = Duration::from_micros(8333);
699 for i in 0..(WARMUP + 10) {
700 monitor.record_work(ms(1), true);
701 monitor.record_work(ms(1), false);
703 monitor.vsync(start + period * i, period);
704 monitor.vsync(start + period * i + period / 2, period);
706 }
707 let snapshot = monitor.snapshot();
708 assert_eq!(snapshot.frames.len(), 10);
709 assert_eq!(snapshot.frame.mean, ms(2));
710 assert!((snapshot.refresh_rate.unwrap() - 120.0).abs() < 0.5);
711 assert!((snapshot.max_fps - 120.0).abs() < 0.5);
713 assert_eq!(snapshot.dropped, 0.0);
714 }
715
716 #[test]
717 fn slow_frames_are_dropped_ones() {
718 let monitor = PerfMonitor::new();
719 let start = Instant::now();
720 let period = ms(16);
721 for i in 0..(WARMUP + 4) {
722 monitor.record_work(if i % 2 == 0 { ms(20) } else { ms(1) }, true);
723 monitor.vsync(start + period * i, period);
724 }
725 assert_eq!(monitor.snapshot().dropped, 0.5);
726 }
727
728 #[test]
729 fn commits_after_warmup() {
730 let monitor = PerfMonitor::new();
731 for _ in 0..(WARMUP + 3) {
732 monitor.record_commit(CommitTiming {
733 js: ms(1),
734 layout: ms(2),
735 ops: 3,
736 items: 4,
737 });
738 }
739 let snapshot = monitor.snapshot();
740 assert_eq!(snapshot.commits, 3.0);
741 assert_eq!(snapshot.js.mean, ms(1));
742 assert_eq!(snapshot.layout.p95, ms(2));
743 assert_eq!(snapshot.items, 4.0);
744 }
745
746 #[test]
747 fn process_sample_reads_memory() {
748 let mut sampler = ProcessSampler::new();
749 let first = sampler.sample();
750 assert_eq!(first.cpu, None);
751 #[cfg(any(target_vendor = "apple", target_os = "linux"))]
752 assert!(first.memory.is_some_and(|m| m > 0));
753 std::thread::sleep(CPU_MIN_SPAN);
754 #[cfg(unix)]
755 assert!(sampler.sample().cpu.is_some());
756 }
757
758 #[test]
762 fn cpu_is_a_rate_over_the_window() {
763 let mut sampler = ProcessSampler::new();
764 let start = Instant::now();
765 let at = |ms: u64| start + Duration::from_millis(ms);
766 let near = |rate: Option<f32>, expected: f64| {
767 rate.is_some_and(|r| (r as f64 - expected).abs() < 0.01)
768 };
769 assert_eq!(sampler.rate(ms(0), at(0)), None);
770 assert_eq!(sampler.rate(ms(5), at(10)), None);
772 assert!(near(sampler.rate(ms(50), at(500)), 10.0));
773 assert!(near(sampler.rate(ms(100), at(1000)), 10.0));
776 assert!(near(
777 sampler.rate(ms(104), at(1004)),
778 104.0 / 1004.0 * 100.0
779 ));
780 sampler.rate(ms(1100), at(2000));
782 assert!(near(sampler.rate(ms(2100), at(3000)), 100.0));
783 }
784
785 #[cfg(target_os = "macos")]
789 #[test]
790 fn footprint_matches_proc_pid_rusage() {
791 let ours = super::memory().expect("task_info");
792 let mut info = std::mem::MaybeUninit::<libc::rusage_info_v2>::uninit();
793 let status = unsafe {
796 libc::proc_pid_rusage(
797 std::process::id() as libc::c_int,
798 libc::RUSAGE_INFO_V2,
799 info.as_mut_ptr().cast::<libc::rusage_info_t>(),
800 )
801 };
802 assert_eq!(status, 0);
803 let theirs = unsafe { info.assume_init() }.ri_phys_footprint;
805 assert!(ours.abs_diff(theirs) < 8 << 20, "{ours} vs {theirs}");
806 }
807}