oxedyne/fe2o3/fe2o3_core/src/mem.rs
1.1 KiB, 6 runs
created by r1870400018:110, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | /// Credit: https://stackoverflow.com/users/4498831/boiethios |
| 2 | /// https://stackoverflow.com/questions/57685567/how-to-move-values-out-of-a-vector-when-the-vector-is-immediately-discarded |
| 3 | pub trait Extract: Default { |
| 4 | fn extract(&mut self) -> Self; |
| 5 | } |
| 6 | |
| 7 | impl<T: Default> Extract for T { |
| 8 | fn extract(&mut self) -> Self { |
| 9 | std::mem::replace(self, T::default()) |
| 10 | } |
| 11 | } |
| 12 | |
| 13 | /// Gets current memory usage in MB. |
| 14 | /// |
| 15 | /// Returns the current process memory usage (VmRSS) in megabytes. |
| 16 | /// On non-Linux systems or if unable to read memory stats, returns 0.0. |
| 17 | pub fn get_memory_usage_mb() -> f32 { |
| 18 | // Simple approach: read from /proc/self/status on Linux. |
| 19 | if let Ok(status) = std::fs::read_to_string("/proc/self/status") { |
| 20 | for line in status.lines() { |
| 21 | if line.starts_with("VmRSS:") { |
| 22 | if let Some(kb_str) = line.split_whitespace().nth(1) { |
| 23 | if let Ok(kb) = kb_str.parse::<u64>() { |
| 24 | return kb as f32 / 1024.0; // Convert KB to MB. |
| 25 | } |
| 26 | } |
| 27 | } |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | // Fallback: return 0 if we can't read memory usage. |
| 32 | 0.0 |
| 33 | } |