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 COMMIT_WINDOW: Duration = Duration::from_secs(5);
109
110const COMMIT_CAPACITY: usize = 1024;
113
114const GC_WINDOW: Duration = Duration::from_secs(10);
117
118const RATE_WINDOW: Duration = Duration::from_secs(1);
120
121const WARMUP: u32 = 4;
125
126#[derive(Debug, Clone, Copy, Default, PartialEq)]
128pub struct CommitTiming {
129 pub js: Duration,
133 pub layout: Duration,
136 pub ops: u32,
138 pub items: u32,
140}
141
142#[derive(Debug, Clone, Copy, Default, PartialEq)]
144pub struct Stat {
145 pub mean: Duration,
147 pub p50: Duration,
149 pub p95: Duration,
151 pub max: Duration,
153}
154
155impl Stat {
156 fn of(samples: impl Iterator<Item = Duration>) -> Stat {
157 let mut sorted: Vec<Duration> = samples.collect();
158 if sorted.is_empty() {
159 return Stat::default();
160 }
161 sorted.sort_unstable();
162 let sum: Duration = sorted.iter().sum();
163 let at = |q: f32| ((sorted.len() as f32 * q).ceil() as usize).clamp(1, sorted.len()) - 1;
164 let p95 = at(0.95);
165 Stat {
166 mean: sum / sorted.len() as u32,
167 p50: sorted[at(0.5)],
168 p95: sorted[p95],
169 max: sorted[sorted.len() - 1],
170 }
171 }
172}
173
174#[derive(Debug, Clone, Copy, Default, PartialEq)]
176pub struct ProcessSample {
177 pub cpu: Option<f32>,
181 pub memory: Option<u64>,
185 pub gpu: Option<f32>,
188}
189
190#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
193pub struct MemorySample {
194 pub js_heap: u64,
196 pub js_objects: u64,
198 pub nodes: u64,
200 pub node_ids: u64,
203}
204
205#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
211pub struct GcSample {
212 pub count: u32,
214 pub longest: Duration,
216}
217
218#[derive(Debug, Clone, Default, PartialEq)]
220pub struct PerfSnapshot {
221 pub fps: f32,
225 pub max_fps: f32,
228 pub refresh_rate: Option<f32>,
230 pub tick_interval: Stat,
234 pub frame_interval: Stat,
237 pub frame: Stat,
240 pub dropped: f32,
242 pub commits: f32,
244 pub js: Stat,
247 pub layout: Stat,
249 pub items: f32,
251 pub latency: Stat,
254 pub engine_busy: f32,
256 pub frames: Vec<Duration>,
258 pub process: ProcessSample,
260 pub memory: Option<MemorySample>,
263 pub gc: GcSample,
265}
266
267impl PerfSnapshot {
268 pub fn stats(&self) -> nsh_core::platform::PerfStats {
270 let mut stats = nsh_core::platform::PerfStats::new(self.fps);
271 stats.refresh_rate = self.refresh_rate;
272 stats.dropped = nsh_core::geometry::Percentage(self.dropped);
273 stats.memory = self.process.memory;
274 stats
275 }
276}
277
278#[derive(Debug)]
281pub struct PerfMonitor {
282 inner: Mutex<Inner>,
283}
284
285#[derive(Debug)]
286struct Inner {
287 pending: Duration,
290 dirty: bool,
291 frames: VecDeque<(Instant, Duration)>,
293 frame_warmup: u32,
294 refresh: Option<f32>,
295 last_vsync: Option<Instant>,
298 ticks: VecDeque<Duration>,
299 commits: VecDeque<(Instant, CommitTiming)>,
300 commit_warmup: u32,
301 latencies: VecDeque<Duration>,
302 busy: VecDeque<(Instant, Duration)>,
304 process: ProcessSample,
305 memory: Option<MemorySample>,
306 gcs: VecDeque<(Instant, Duration)>,
308}
309
310impl Default for PerfMonitor {
311 fn default() -> Self {
312 PerfMonitor {
313 inner: Mutex::new(Inner {
314 pending: Duration::ZERO,
315 dirty: false,
316 frames: VecDeque::with_capacity(CAPACITY),
317 frame_warmup: WARMUP,
318 refresh: None,
319 last_vsync: None,
320 ticks: VecDeque::with_capacity(CAPACITY),
321 commits: VecDeque::new(),
322 commit_warmup: WARMUP,
323 latencies: VecDeque::with_capacity(CAPACITY),
324 busy: VecDeque::new(),
325 process: ProcessSample::default(),
326 memory: None,
327 gcs: VecDeque::new(),
328 }),
329 }
330 }
331}
332
333fn push<T>(queue: &mut VecDeque<T>, value: T) {
334 if queue.len() == CAPACITY {
335 queue.pop_front();
336 }
337 queue.push_back(value);
338}
339
340impl PerfMonitor {
341 pub fn new() -> PerfMonitor {
343 PerfMonitor::default()
344 }
345
346 fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
347 self.inner.lock().unwrap_or_else(|e| e.into_inner())
348 }
349
350 pub fn record_work(&self, cost: Duration, dirty: bool) {
354 let mut inner = self.lock();
355 inner.pending += cost;
356 inner.dirty |= dirty;
357 }
358
359 pub fn vsync(&self, at: Instant, interval: Duration) {
363 let mut inner = self.lock();
364 if interval > Duration::ZERO {
365 let rate = 1.0 / interval.as_secs_f32();
366 inner.refresh = Some(match inner.refresh {
368 Some(r) if (r - rate).abs() < r * 0.1 => r + (rate - r) * 0.1,
369 _ => rate,
370 });
371 }
372 if let Some(last) = inner.last_vsync.replace(at) {
373 let gap = at.duration_since(last);
374 if gap < Duration::from_millis(100) {
377 push(&mut inner.ticks, gap);
378 }
379 }
380 let cost = std::mem::take(&mut inner.pending);
381 if !std::mem::take(&mut inner.dirty) {
382 return;
383 }
384 if inner.frame_warmup > 0 {
385 inner.frame_warmup -= 1;
386 return;
387 }
388 push(&mut inner.frames, (at, cost));
389 }
390
391 pub fn record_latency(&self, latency: Duration) {
394 let mut inner = self.lock();
395 if inner.frame_warmup == 0 {
397 push(&mut inner.latencies, latency);
398 }
399 }
400
401 pub fn record_commit(&self, timing: CommitTiming) {
403 self.record_commit_at(Instant::now(), timing);
404 }
405
406 fn record_commit_at(&self, at: Instant, timing: CommitTiming) {
407 let mut inner = self.lock();
408 if inner.commit_warmup > 0 {
409 inner.commit_warmup -= 1;
410 return;
411 }
412 let commits = &mut inner.commits;
413 while commits.front().is_some_and(|&(then, _)| {
414 commits.len() >= COMMIT_CAPACITY || at.duration_since(then) > COMMIT_WINDOW
415 }) {
416 commits.pop_front();
417 }
418 commits.push_back((at, timing));
419 }
420
421 pub fn record_busy(&self, busy: Duration) {
423 let now = Instant::now();
424 let mut inner = self.lock();
425 inner.busy.push_back((now, busy));
426 while inner
427 .busy
428 .front()
429 .is_some_and(|&(at, _)| now.duration_since(at) > RATE_WINDOW)
430 {
431 inner.busy.pop_front();
432 }
433 }
434
435 pub fn set_process(&self, sample: ProcessSample) {
438 self.lock().process = sample;
439 }
440
441 pub fn record_gc(&self, pause: Duration) {
443 self.record_gc_at(Instant::now(), pause);
444 }
445
446 fn record_gc_at(&self, at: Instant, pause: Duration) {
447 let mut inner = self.lock();
448 while inner
449 .gcs
450 .front()
451 .is_some_and(|&(then, _)| at.duration_since(then) > GC_WINDOW)
452 {
453 inner.gcs.pop_front();
454 }
455 inner.gcs.push_back((at, pause));
456 }
457
458 pub fn set_memory(&self, sample: MemorySample) {
460 self.lock().memory = Some(sample);
461 }
462
463 pub fn snapshot(&self) -> PerfSnapshot {
465 self.snapshot_at(Instant::now())
466 }
467
468 fn snapshot_at(&self, now: Instant) -> PerfSnapshot {
469 let inner = self.lock();
470 let recent = |at: Instant| now.duration_since(at) <= RATE_WINDOW;
471 let shown: Vec<Instant> = inner
474 .frames
475 .iter()
476 .map(|&(at, _)| at)
477 .filter(|&at| recent(at))
478 .collect();
479 let fps = match (shown.first(), shown.last()) {
480 (Some(&first), Some(&last)) if shown.len() >= 2 && last > first => {
481 let span = now.duration_since(first).max(last.duration_since(first));
484 (shown.len() - 1) as f32 / span.as_secs_f32()
485 }
486 _ => 0.0,
487 };
488 let frame = Stat::of(inner.frames.iter().map(|&(_, cost)| cost));
489 let budget = Duration::from_secs_f32(1.0 / inner.refresh.unwrap_or(60.0));
490 let dropped = match inner.frames.len() {
491 0 => 0.0,
492 n => {
493 inner
494 .frames
495 .iter()
496 .filter(|&&(_, cost)| cost > budget)
497 .count() as f32
498 / n as f32
499 }
500 };
501 let max_fps = if frame.mean > Duration::ZERO {
502 let max = 1.0 / frame.mean.as_secs_f32();
503 inner.refresh.map_or(max, |r| max.min(r))
504 } else {
505 0.0
506 };
507 let commits = inner.commits.iter().filter(|&&(at, _)| recent(at)).count() as f32;
508 let windowed: Vec<CommitTiming> = inner
510 .commits
511 .iter()
512 .filter(|&&(at, _)| now.duration_since(at) <= COMMIT_WINDOW)
513 .map(|&(_, c)| c)
514 .collect();
515 let items = match windowed.len() {
516 0 => 0.0,
517 n => windowed.iter().map(|c| c.items as f32).sum::<f32>() / n as f32,
518 };
519 let busy: Duration = inner
520 .busy
521 .iter()
522 .filter(|&&(at, _)| recent(at))
523 .map(|&(_, d)| d)
524 .sum();
525 PerfSnapshot {
526 fps,
527 max_fps,
528 refresh_rate: inner.refresh,
529 tick_interval: Stat::of(inner.ticks.iter().copied()),
530 frame_interval: Stat::of(
531 inner
532 .frames
533 .iter()
534 .zip(inner.frames.iter().skip(1))
535 .map(|(&(a, _), &(b, _))| b.duration_since(a)),
536 ),
537 frame,
538 dropped,
539 commits,
540 js: Stat::of(windowed.iter().map(|c| c.js)),
541 layout: Stat::of(windowed.iter().map(|c| c.layout)),
542 items,
543 latency: Stat::of(inner.latencies.iter().copied()),
544 engine_busy: busy.as_secs_f32() / RATE_WINDOW.as_secs_f32() * 100.0,
545 frames: inner.frames.iter().map(|&(_, cost)| cost).collect(),
546 process: inner.process,
547 memory: inner.memory,
548 gc: {
549 let window = inner
550 .gcs
551 .iter()
552 .filter(|&&(at, _)| now.duration_since(at) <= GC_WINDOW);
553 GcSample {
554 count: window.clone().count() as u32,
555 longest: window.map(|&(_, pause)| pause).max().unwrap_or_default(),
556 }
557 },
558 }
559 }
560}
561
562pub const CPU_WINDOW: Duration = Duration::from_secs(1);
568
569const CPU_MIN_SPAN: Duration = Duration::from_millis(250);
572
573#[derive(Debug)]
578pub struct ProcessSampler {
579 readings: VecDeque<(Duration, Instant)>,
582}
583
584impl Default for ProcessSampler {
585 fn default() -> Self {
586 ProcessSampler::new()
587 }
588}
589
590impl ProcessSampler {
591 pub fn new() -> ProcessSampler {
593 ProcessSampler {
594 readings: VecDeque::new(),
595 }
596 }
597
598 pub fn sample(&mut self) -> ProcessSample {
601 let now = Instant::now();
602 ProcessSample {
603 cpu: cpu_time().and_then(|used| self.rate(used, now)),
604 memory: memory(),
605 gpu: None,
606 }
607 }
608
609 fn rate(&mut self, used: Duration, now: Instant) -> Option<f32> {
612 self.readings.push_back((used, now));
613 while self
614 .readings
615 .get(1)
616 .is_some_and(|(_, at)| now.duration_since(*at) >= CPU_WINDOW)
617 {
618 self.readings.pop_front();
619 }
620 let (base, at) = *self.readings.front()?;
621 let span = now.duration_since(at);
622 (span >= CPU_MIN_SPAN)
623 .then(|| used.saturating_sub(base).as_secs_f32() / span.as_secs_f32() * 100.0)
624 }
625}
626
627#[cfg(unix)]
629fn cpu_time() -> Option<Duration> {
630 let mut usage = std::mem::MaybeUninit::<libc::rusage>::uninit();
631 if unsafe { libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) } != 0 {
633 return None;
634 }
635 let usage = unsafe { usage.assume_init() };
637 let time = |t: libc::timeval| Duration::new(t.tv_sec as u64, t.tv_usec as u32 * 1000);
638 Some(time(usage.ru_utime) + time(usage.ru_stime))
639}
640
641#[cfg(windows)]
642fn cpu_time() -> Option<Duration> {
643 use windows_sys::Win32::{
644 Foundation::FILETIME,
645 System::Threading::{GetCurrentProcess, GetProcessTimes},
646 };
647 let zero = FILETIME {
648 dwLowDateTime: 0,
649 dwHighDateTime: 0,
650 };
651 let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero);
652 let ok = unsafe {
654 GetProcessTimes(
655 GetCurrentProcess(),
656 &mut created,
657 &mut exited,
658 &mut kernel,
659 &mut user,
660 )
661 };
662 let ticks = |t: FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime);
664 (ok != 0).then(|| Duration::from_nanos((ticks(kernel) + ticks(user)) * 100))
665}
666
667#[cfg(not(any(unix, windows)))]
668fn cpu_time() -> Option<Duration> {
669 None
670}
671
672#[cfg(target_vendor = "apple")]
680fn memory() -> Option<u64> {
681 #[repr(C)]
685 struct TaskVmInfo {
686 before: [u64; 18],
689 phys_footprint: u64,
690 }
691 unsafe extern "C" {
692 static mach_task_self_: libc::mach_port_t;
695 }
696 const TASK_VM_INFO: libc::task_flavor_t = 22;
697 const _: () = assert!(std::mem::size_of::<TaskVmInfo>() == 152);
698 let words = std::mem::size_of::<TaskVmInfo>() / std::mem::size_of::<libc::natural_t>();
699 let mut count = words as libc::mach_msg_type_number_t;
700 let mut info = std::mem::MaybeUninit::<TaskVmInfo>::uninit();
701 let status = unsafe {
705 libc::task_info(
706 mach_task_self_,
707 TASK_VM_INFO,
708 info.as_mut_ptr().cast::<libc::integer_t>(),
709 &mut count,
710 )
711 };
712 (status == libc::KERN_SUCCESS && count as usize == words)
714 .then(|| unsafe { info.assume_init() }.phys_footprint)
715}
716
717#[cfg(any(target_os = "linux", target_os = "android"))]
719fn memory() -> Option<u64> {
720 let statm = std::fs::read_to_string("/proc/self/statm").ok()?;
721 let pages: u64 = statm.split_whitespace().nth(1)?.parse().ok()?;
722 let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
724 Some(pages * u64::try_from(page).ok()?)
725}
726
727#[cfg(windows)]
729fn memory() -> Option<u64> {
730 use windows_sys::Win32::System::{
731 ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS},
732 Threading::GetCurrentProcess,
733 };
734 let mut counters: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() };
736 counters.cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
737 let ok = unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) };
739 (ok != 0).then_some(counters.WorkingSetSize as u64)
740}
741
742#[cfg(not(any(
743 target_vendor = "apple",
744 target_os = "linux",
745 target_os = "android",
746 windows
747)))]
748fn memory() -> Option<u64> {
749 None
750}
751
752#[cfg(test)]
753mod tests {
754 use super::*;
755
756 fn ms(ms: u64) -> Duration {
757 Duration::from_millis(ms)
758 }
759
760 #[test]
761 fn stat_of_samples() {
762 let stat = Stat::of((1..=20).map(ms));
763 assert_eq!(stat.mean, Duration::from_micros(10_500));
764 assert_eq!(stat.p50, ms(10));
765 assert_eq!(stat.p95, ms(19));
766 assert_eq!(stat.max, ms(20));
767 assert_eq!(Stat::of(std::iter::empty()), Stat::default());
768 }
769
770 #[test]
771 fn frames_are_refreshes_that_changed_something() {
772 let monitor = PerfMonitor::new();
773 let start = Instant::now();
774 let period = Duration::from_micros(8333);
775 for i in 0..(WARMUP + 10) {
776 monitor.record_work(ms(1), true);
777 monitor.record_work(ms(1), false);
779 monitor.vsync(start + period * i, period);
780 monitor.vsync(start + period * i + period / 2, period);
782 }
783 let snapshot = monitor.snapshot();
784 assert_eq!(snapshot.frames.len(), 10);
785 assert_eq!(snapshot.frame.mean, ms(2));
786 assert!((snapshot.refresh_rate.unwrap() - 120.0).abs() < 0.5);
787 assert!((snapshot.max_fps - 120.0).abs() < 0.5);
789 assert_eq!(snapshot.dropped, 0.0);
790 }
791
792 #[test]
793 fn slow_frames_are_dropped_ones() {
794 let monitor = PerfMonitor::new();
795 let start = Instant::now();
796 let period = ms(16);
797 for i in 0..(WARMUP + 4) {
798 monitor.record_work(if i % 2 == 0 { ms(20) } else { ms(1) }, true);
799 monitor.vsync(start + period * i, period);
800 }
801 assert_eq!(monitor.snapshot().dropped, 0.5);
802 }
803
804 #[test]
805 fn commits_after_warmup() {
806 let monitor = PerfMonitor::new();
807 for _ in 0..(WARMUP + 3) {
808 monitor.record_commit(CommitTiming {
809 js: ms(1),
810 layout: ms(2),
811 ops: 3,
812 items: 4,
813 });
814 }
815 let snapshot = monitor.snapshot();
816 assert_eq!(snapshot.commits, 3.0);
817 assert_eq!(snapshot.js.mean, ms(1));
818 assert_eq!(snapshot.layout.p95, ms(2));
819 assert_eq!(snapshot.items, 4.0);
820 }
821
822 #[test]
826 fn commits_over_a_time_window() {
827 let monitor = PerfMonitor::new();
828 let start = Instant::now();
829 let commit = |js| CommitTiming {
830 js: ms(js),
831 layout: ms(1),
832 ops: 1,
833 items: 2,
834 };
835 for _ in 0..WARMUP {
836 monitor.record_commit_at(start, commit(0));
837 }
838 let mut at = start;
840 for _ in 0..120 {
841 at += Duration::from_micros(16_667);
842 monitor.record_commit_at(at, commit(12));
843 }
844 for _ in 0..8 {
846 at += Duration::from_secs(1);
847 monitor.record_commit_at(at, commit(2));
848 }
849 let snapshot = monitor.snapshot_at(at);
850 assert_eq!(snapshot.js.max, ms(2));
851 assert_eq!(snapshot.js.p95, ms(2));
852 assert_eq!(snapshot.items, 2.0);
853 assert!(monitor.lock().commits.len() <= 6);
855 let snapshot = monitor.snapshot_at(at + COMMIT_WINDOW + ms(1));
857 assert_eq!(snapshot.js, Stat::default());
858 assert_eq!(snapshot.items, 0.0);
859 }
860
861 #[test]
862 fn commits_kept_are_bounded() {
863 let monitor = PerfMonitor::new();
864 let start = Instant::now();
865 for i in 0..(WARMUP + 3000) {
866 monitor.record_commit_at(
867 start + Duration::from_micros(i.into()),
868 CommitTiming::default(),
869 );
870 }
871 assert_eq!(monitor.lock().commits.len(), COMMIT_CAPACITY);
872 }
873
874 #[test]
876 fn collections_over_a_time_window() {
877 let ms = Duration::from_millis;
878 let monitor = PerfMonitor::new();
879 let start = Instant::now();
880 assert_eq!(monitor.snapshot_at(start).gc, GcSample::default());
881 monitor.record_gc_at(start, ms(90));
882 monitor.record_gc_at(start + ms(5000), ms(30));
883 monitor.record_gc_at(start + ms(9000), ms(40));
884 let at = start + ms(9000);
885 assert_eq!(
886 monitor.snapshot_at(at).gc,
887 GcSample {
888 count: 3,
889 longest: ms(90)
890 }
891 );
892 let at = start + GC_WINDOW + ms(1);
894 assert_eq!(
895 monitor.snapshot_at(at).gc,
896 GcSample {
897 count: 2,
898 longest: ms(40)
899 }
900 );
901 monitor.record_gc_at(start + ms(20_000), ms(10));
902 assert_eq!(monitor.lock().gcs.len(), 1);
903 }
904
905 #[test]
906 fn process_sample_reads_memory() {
907 let mut sampler = ProcessSampler::new();
908 let first = sampler.sample();
909 assert_eq!(first.cpu, None);
910 #[cfg(any(target_vendor = "apple", target_os = "linux"))]
911 assert!(first.memory.is_some_and(|m| m > 0));
912 std::thread::sleep(CPU_MIN_SPAN);
913 #[cfg(unix)]
914 assert!(sampler.sample().cpu.is_some());
915 }
916
917 #[test]
921 fn cpu_is_a_rate_over_the_window() {
922 let mut sampler = ProcessSampler::new();
923 let start = Instant::now();
924 let at = |ms: u64| start + Duration::from_millis(ms);
925 let near = |rate: Option<f32>, expected: f64| {
926 rate.is_some_and(|r| (r as f64 - expected).abs() < 0.01)
927 };
928 assert_eq!(sampler.rate(ms(0), at(0)), None);
929 assert_eq!(sampler.rate(ms(5), at(10)), None);
931 assert!(near(sampler.rate(ms(50), at(500)), 10.0));
932 assert!(near(sampler.rate(ms(100), at(1000)), 10.0));
935 assert!(near(
936 sampler.rate(ms(104), at(1004)),
937 104.0 / 1004.0 * 100.0
938 ));
939 sampler.rate(ms(1100), at(2000));
941 assert!(near(sampler.rate(ms(2100), at(3000)), 100.0));
942 }
943
944 #[cfg(target_os = "macos")]
948 #[test]
949 fn footprint_matches_proc_pid_rusage() {
950 let ours = super::memory().expect("task_info");
951 let mut info = std::mem::MaybeUninit::<libc::rusage_info_v2>::uninit();
952 let status = unsafe {
955 libc::proc_pid_rusage(
956 std::process::id() as libc::c_int,
957 libc::RUSAGE_INFO_V2,
958 info.as_mut_ptr().cast::<libc::rusage_info_t>(),
959 )
960 };
961 assert_eq!(status, 0);
962 let theirs = unsafe { info.assume_init() }.ri_phys_footprint;
964 assert!(ours.abs_diff(theirs) < 8 << 20, "{ours} vs {theirs}");
965 }
966}