Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Refactor macOS memory usage reporting to use libproc
Richie McIlroy04066dd02bf0
diff --git a/crates/recording/examples/memory-leak-detector.rs b/crates/recording/examples/memory-leak-detector.rsindex 0e7776573..efb5c7004 100644--- a/crates/recording/examples/memory-leak-detector.rs+++ b/crates/recording/examples/memory-leak-detector.rs@@ -18,106 +18,19 @@ const DEFAULT_DURATION_SECS: u64 = 120;#[cfg(target_os = "macos")]fn get_memory_usage() -> Option<MemoryStats> {- use std::process::Command;+ use libproc::libproc::pid_rusage::{RUsageInfoV4, pidrusage};- let pid = std::process::id();-- let ps_output = Command::new("ps")- .args(["-o", "rss=,vsz=", "-p", &pid.to_string()])- .output()- .ok()?;-- let stdout = String::from_utf8_lossy(&ps_output.stdout);- let parts: Vec<&str> = stdout.split_whitespace().collect();-- let (rss_mb, vsz_mb) = if parts.len() >= 2 {- let rss_kb: u64 = parts[0].parse().ok()?;- let vsz_kb: u64 = parts[1].parse().ok()?;- (rss_kb as f64 / 1024.0, vsz_kb as f64 / 1024.0)- } else {- return None;- };-- let (footprint_mb, dirty_mb) = Command::new("footprint")- .arg(pid.to_string())- .output()- .ok()- .filter(|o| o.status.success())- .and_then(|output| {- let stdout = String::from_utf8_lossy(&output.stdout);- parse_footprint_values(&stdout)- })- .unwrap_or((None, None));+ let pid = std::process::id() as i32;+ let rusage: RUsageInfoV4 = pidrusage(pid).ok()?;Some(MemoryStats {- resident_mb: rss_mb,- virtual_mb: vsz_mb,- footprint_mb,- dirty_mb,+ resident_mb: rusage.ri_resident_size as f64 / 1024.0 / 1024.0,+ footprint_mb: Some(rusage.ri_phys_footprint as f64 / 1024.0 / 1024.0),+ dirty_mb: None,compressed_mb: None,})}-#[cfg(target_os = "macos")]-fn parse_footprint_values(output: &str) -> Option<(Option<f64>, Option<f64>)> {- let mut footprint_kb: Option<f64> = None;- let mut dirty_kb: Option<f64> = None;-- for line in output.lines() {- if line.contains("phys_footprint:") {- let parts: Vec<&str> = line.split_whitespace().collect();- if parts.len() >= 2 {- footprint_kb = parse_size_kb(parts[1]);- }- } else if line.contains("TOTAL") && dirty_kb.is_none() {- let parts: Vec<&str> = line.split_whitespace().collect();- if !parts.is_empty() {- dirty_kb = parse_size_kb(parts[0]);- }- }- }-- Some((- footprint_kb.map(|v| v / 1024.0),- dirty_kb.map(|v| v / 1024.0),- ))-}--#[cfg(target_os = "macos")]-fn parse_size_kb(s: &str) -> Option<f64> {- let s = s.trim();- if s.ends_with("KB") || s.ends_with("kb") {- s.trim_end_matches("KB")- .trim_end_matches("kb")- .trim()- .parse()- .ok()- } else if s.ends_with("MB") || s.ends_with("mb") {- s.trim_end_matches("MB")- .trim_end_matches("mb")- .trim()- .parse::<f64>()- .ok()- .map(|v| v * 1024.0)- } else if s.ends_with("GB") || s.ends_with("gb") {- s.trim_end_matches("GB")- .trim_end_matches("gb")- .trim()- .parse::<f64>()- .ok()- .map(|v| v * 1024.0 * 1024.0)- } else if s.ends_with('B') || s.ends_with('b') {- s.trim_end_matches('B')- .trim_end_matches('b')- .trim()- .parse::<f64>()- .ok()- .map(|v| v / 1024.0)- } else {- s.parse().ok()- }-}-#[cfg(not(target_os = "macos"))]fn get_memory_usage() -> Option<MemoryStats> {None@@ -126,7 +39,6 @@ fn get_memory_usage() -> Option<MemoryStats> {#[derive(Debug, Clone, Copy)]struct MemoryStats {resident_mb: f64,- virtual_mb: f64,footprint_mb: Option<f64>,#[allow(dead_code)]dirty_mb: Option<f64>,@@ -136,11 +48,11 @@ struct MemoryStats {impl MemoryStats {fn primary_metric(&self) -> f64 {- self.resident_mb+ self.footprint_mb.unwrap_or(self.resident_mb)}fn metric_name() -> &'static str {- "RSS"+ "Footprint"}}@@ -170,10 +82,10 @@ impl MemoryTracker {if let Some(baseline) = self.baseline {println!(- "Baseline: {:.1} MB {} (Footprint: {:.1} MB)",+ "Baseline: {:.1} MB {} (RSS: {:.1} MB)",baseline.primary_metric(),MemoryStats::metric_name(),- baseline.footprint_mb.unwrap_or(0.0)+ baseline.resident_mb);}@@ -195,10 +107,10 @@ impl MemoryTracker {println!("\nMemory Timeline:");println!(- "{:>8} {:>12} {:>12} {:>12} {:>12}",- "Time(s)", "RSS(MB)", "Delta", "Footprint", "VSZ(MB)"+ "{:>8} {:>14} {:>10} {:>12}",+ "Time(s)", "Footprint(MB)", "Delta", "RSS(MB)");- println!("{:-<70}", "");+ println!("{:-<50}", "");let mut prev_memory = first.1.primary_metric();for (time, stats) in &self.samples {@@ -210,20 +122,19 @@ impl MemoryTracker {"~0".to_string()};println!(- "{:>8.1} {:>12.1} {:>12} {:>12.1} {:>12.1}",+ "{:>8.1} {:>14.1} {:>10} {:>12.1}",time.as_secs_f64(),current,delta_str,- stats.footprint_mb.unwrap_or(0.0),- stats.virtual_mb+ stats.resident_mb);prev_memory = current;}println!("\n=== Summary ===");println!("Duration: {duration_secs:.1}s");- println!("Start RSS: {:.1} MB", first.1.primary_metric());- println!("End RSS: {:.1} MB", last.1.primary_metric());+ println!("Start Footprint: {:.1} MB", first.1.primary_metric());+ println!("End Footprint: {:.1} MB", last.1.primary_metric());println!("Total growth: {memory_growth:.1} MB");println!("Growth rate: {:.2} MB/s ({:.1} MB/10s)",@@ -251,7 +162,7 @@ impl MemoryTracker {}println!(- "\nPeak RSS: {:.1} MB",+ "\nPeak Footprint: {:.1} MB",self.samples.iter().map(|(_, s)| s.primary_metric())@@ -344,7 +255,7 @@ async fn run_memory_test().await?;- let sample_interval = Duration::from_secs(5);+ let sample_interval = Duration::from_secs(1);let mut next_sample = start + sample_interval;while start.elapsed() < Duration::from_secs(duration_secs) {@@ -355,11 +266,10 @@ async fn run_memory_test(let current = get_memory_usage();if let Some(stats) = current {println!(- "[{:>5.1}s] RSS: {:.1} MB, Footprint: {:.1} MB, VSZ: {:.1} MB",+ "[{:>5.1}s] Footprint: {:.1} MB, RSS: {:.1} MB",start.elapsed().as_secs_f64(),- stats.resident_mb,stats.footprint_mb.unwrap_or(0.0),- stats.virtual_mb+ stats.resident_mb);}next_sample = Instant::now() + sample_interval;@@ -407,7 +317,7 @@ async fn run_camera_only_test(duration_secs: u64) -> Result<(), Box<dyn std::err.await?;let start = Instant::now();- let sample_interval = Duration::from_secs(5);+ let sample_interval = Duration::from_secs(1);let mut next_sample = start + sample_interval;let mut frame_count = 0u64;@@ -428,10 +338,10 @@ async fn run_camera_only_test(duration_secs: u64) -> Result<(), Box<dyn std::errlet queue_len = frame_rx.len();if let Some(stats) = current {println!(- "[{:>5.1}s] RSS: {:.1} MB, Footprint: {:.1} MB, Frames: {}, Queue: {}",+ "[{:>5.1}s] Footprint: {:.1} MB, RSS: {:.1} MB, Frames: {}, Queue: {}",start.elapsed().as_secs_f64(),- stats.resident_mb,stats.footprint_mb.unwrap_or(0.0),+ stats.resident_mb,frame_count,queue_len);