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(not(unix))]
437fn cpu_time() -> Option<Duration> {
438 None
439}
440
441#[cfg(target_vendor = "apple")]
446fn memory() -> Option<u64> {
447 unsafe extern "C" {
448 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 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 (status == 0).then(|| unsafe { info.assume_init() }.ri_phys_footprint)
468}
469
470#[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 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 monitor.record_work(ms(1), false);
512 monitor.vsync(start + period * i, period);
513 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 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}