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