1use std::{collections::VecDeque, sync::Mutex, time::Duration};
31
32use nsh_core::time::Instant;
33
34const CAPACITY: usize = 120;
36
37const RATE_WINDOW: Duration = Duration::from_secs(1);
39
40const WARMUP: u32 = 4;
44
45#[derive(Debug, Clone, Copy, Default, PartialEq)]
47pub struct CommitTiming {
48 pub js: Duration,
52 pub layout: Duration,
55 pub ops: u32,
57 pub items: u32,
59}
60
61#[derive(Debug, Clone, Copy, Default, PartialEq)]
63pub struct Stat {
64 pub mean: Duration,
66 pub p50: Duration,
68 pub p95: Duration,
70 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#[derive(Debug, Clone, Copy, Default, PartialEq)]
95pub struct ProcessSample {
96 pub cpu: Option<f32>,
100 pub memory: Option<u64>,
104 pub gpu: Option<f32>,
107}
108
109#[derive(Debug, Clone, Default, PartialEq)]
111pub struct PerfSnapshot {
112 pub fps: f32,
116 pub max_fps: f32,
119 pub refresh_rate: Option<f32>,
121 pub tick_interval: Stat,
125 pub frame_interval: Stat,
128 pub frame: Stat,
131 pub dropped: f32,
133 pub commits: f32,
135 pub js: Stat,
137 pub layout: Stat,
139 pub items: f32,
141 pub latency: Stat,
144 pub engine_busy: f32,
146 pub frames: Vec<Duration>,
148 pub process: ProcessSample,
150}
151
152#[derive(Debug)]
155pub struct PerfMonitor {
156 inner: Mutex<Inner>,
157}
158
159#[derive(Debug)]
160struct Inner {
161 pending: Duration,
164 dirty: bool,
165 frames: VecDeque<(Instant, Duration)>,
167 frame_warmup: u32,
168 refresh: Option<f32>,
169 last_vsync: Option<Instant>,
172 ticks: VecDeque<Duration>,
173 commits: VecDeque<(Instant, CommitTiming)>,
174 commit_warmup: u32,
175 latencies: VecDeque<Duration>,
176 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 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 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 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 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 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 pub fn record_latency(&self, latency: Duration) {
263 let mut inner = self.lock();
264 if inner.frame_warmup == 0 {
266 push(&mut inner.latencies, latency);
267 }
268 }
269
270 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 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 pub fn set_process(&self, sample: ProcessSample) {
297 self.lock().process = sample;
298 }
299
300 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 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 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#[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 pub fn new() -> ProcessSampler {
402 ProcessSampler { last: None }
403 }
404
405 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#[cfg(unix)]
424fn cpu_time() -> Option<Duration> {
425 let mut usage = std::mem::MaybeUninit::<libc::rusage>::uninit();
426 if unsafe { libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) } != 0 {
428 return None;
429 }
430 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(windows)]
437fn cpu_time() -> Option<Duration> {
438 use windows_sys::Win32::{
439 Foundation::FILETIME,
440 System::Threading::{GetCurrentProcess, GetProcessTimes},
441 };
442 let zero = FILETIME {
443 dwLowDateTime: 0,
444 dwHighDateTime: 0,
445 };
446 let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero);
447 let ok = unsafe {
449 GetProcessTimes(
450 GetCurrentProcess(),
451 &mut created,
452 &mut exited,
453 &mut kernel,
454 &mut user,
455 )
456 };
457 let ticks = |t: FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime);
459 (ok != 0).then(|| Duration::from_nanos((ticks(kernel) + ticks(user)) * 100))
460}
461
462#[cfg(not(any(unix, windows)))]
463fn cpu_time() -> Option<Duration> {
464 None
465}
466
467#[cfg(target_vendor = "apple")]
475fn memory() -> Option<u64> {
476 #[repr(C)]
480 struct TaskVmInfo {
481 before: [u64; 18],
484 phys_footprint: u64,
485 }
486 unsafe extern "C" {
487 static mach_task_self_: libc::mach_port_t;
490 }
491 const TASK_VM_INFO: libc::task_flavor_t = 22;
492 const _: () = assert!(std::mem::size_of::<TaskVmInfo>() == 152);
493 let words = std::mem::size_of::<TaskVmInfo>() / std::mem::size_of::<libc::natural_t>();
494 let mut count = words as libc::mach_msg_type_number_t;
495 let mut info = std::mem::MaybeUninit::<TaskVmInfo>::uninit();
496 let status = unsafe {
500 libc::task_info(
501 mach_task_self_,
502 TASK_VM_INFO,
503 info.as_mut_ptr().cast::<libc::integer_t>(),
504 &mut count,
505 )
506 };
507 (status == libc::KERN_SUCCESS && count as usize == words)
509 .then(|| unsafe { info.assume_init() }.phys_footprint)
510}
511
512#[cfg(any(target_os = "linux", target_os = "android"))]
514fn memory() -> Option<u64> {
515 let statm = std::fs::read_to_string("/proc/self/statm").ok()?;
516 let pages: u64 = statm.split_whitespace().nth(1)?.parse().ok()?;
517 let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
519 Some(pages * u64::try_from(page).ok()?)
520}
521
522#[cfg(windows)]
524fn memory() -> Option<u64> {
525 use windows_sys::Win32::System::{
526 ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS},
527 Threading::GetCurrentProcess,
528 };
529 let mut counters: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() };
531 counters.cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
532 let ok = unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) };
534 (ok != 0).then_some(counters.WorkingSetSize as u64)
535}
536
537#[cfg(not(any(
538 target_vendor = "apple",
539 target_os = "linux",
540 target_os = "android",
541 windows
542)))]
543fn memory() -> Option<u64> {
544 None
545}
546
547#[cfg(test)]
548mod tests {
549 use super::*;
550
551 fn ms(ms: u64) -> Duration {
552 Duration::from_millis(ms)
553 }
554
555 #[test]
556 fn stat_of_samples() {
557 let stat = Stat::of((1..=20).map(ms));
558 assert_eq!(stat.mean, Duration::from_micros(10_500));
559 assert_eq!(stat.p50, ms(10));
560 assert_eq!(stat.p95, ms(19));
561 assert_eq!(stat.max, ms(20));
562 assert_eq!(Stat::of(std::iter::empty()), Stat::default());
563 }
564
565 #[test]
566 fn frames_are_refreshes_that_changed_something() {
567 let monitor = PerfMonitor::new();
568 let start = Instant::now();
569 let period = Duration::from_micros(8333);
570 for i in 0..(WARMUP + 10) {
571 monitor.record_work(ms(1), true);
572 monitor.record_work(ms(1), false);
574 monitor.vsync(start + period * i, period);
575 monitor.vsync(start + period * i + period / 2, period);
577 }
578 let snapshot = monitor.snapshot();
579 assert_eq!(snapshot.frames.len(), 10);
580 assert_eq!(snapshot.frame.mean, ms(2));
581 assert!((snapshot.refresh_rate.unwrap() - 120.0).abs() < 0.5);
582 assert!((snapshot.max_fps - 120.0).abs() < 0.5);
584 assert_eq!(snapshot.dropped, 0.0);
585 }
586
587 #[test]
588 fn slow_frames_are_dropped_ones() {
589 let monitor = PerfMonitor::new();
590 let start = Instant::now();
591 let period = ms(16);
592 for i in 0..(WARMUP + 4) {
593 monitor.record_work(if i % 2 == 0 { ms(20) } else { ms(1) }, true);
594 monitor.vsync(start + period * i, period);
595 }
596 assert_eq!(monitor.snapshot().dropped, 0.5);
597 }
598
599 #[test]
600 fn commits_after_warmup() {
601 let monitor = PerfMonitor::new();
602 for _ in 0..(WARMUP + 3) {
603 monitor.record_commit(CommitTiming {
604 js: ms(1),
605 layout: ms(2),
606 ops: 3,
607 items: 4,
608 });
609 }
610 let snapshot = monitor.snapshot();
611 assert_eq!(snapshot.commits, 3.0);
612 assert_eq!(snapshot.js.mean, ms(1));
613 assert_eq!(snapshot.layout.p95, ms(2));
614 assert_eq!(snapshot.items, 4.0);
615 }
616
617 #[test]
618 fn process_sample_reads_memory() {
619 let mut sampler = ProcessSampler::new();
620 let first = sampler.sample();
621 assert_eq!(first.cpu, None);
622 #[cfg(any(target_vendor = "apple", target_os = "linux"))]
623 assert!(first.memory.is_some_and(|m| m > 0));
624 std::thread::sleep(ms(5));
625 #[cfg(unix)]
626 assert!(sampler.sample().cpu.is_some());
627 }
628
629 #[cfg(target_os = "macos")]
633 #[test]
634 fn footprint_matches_proc_pid_rusage() {
635 let ours = super::memory().expect("task_info");
636 let mut info = std::mem::MaybeUninit::<libc::rusage_info_v2>::uninit();
637 let status = unsafe {
640 libc::proc_pid_rusage(
641 std::process::id() as libc::c_int,
642 libc::RUSAGE_INFO_V2,
643 info.as_mut_ptr().cast::<libc::rusage_info_t>(),
644 )
645 };
646 assert_eq!(status, 0);
647 let theirs = unsafe { info.assume_init() }.ri_phys_footprint;
649 assert!(ours.abs_diff(theirs) < 8 << 20, "{ours} vs {theirs}");
650 }
651}