在篇文章中,我們使用memory-stats crate來報告和分析Rust進程使用了多少內存,它依賴于操作系統的內存計算。
使用以下命令創建一個Rust新項目:
cargo new memory-stats-example
加入以下依賴項:
[dependencies]memory-stats = { version = "1.1.0", features = ["always_use_statm"] }thousands = "0.2.0"
基本上我們分析兩種內存:
在我們的例子中,創建了包含許多字符的變量,在創建變量之前和之后,打印內存差異。
在src/main.rs文件中寫入以下代碼:
use memory_stats::memory_stats;use thousands::Separable;fn main() { show_mem(); println!(" 字節 物理內存 虛擬內存 "); check_mem(10000); check_mem(100000); check_mem(1000000); check_mem(10000000); check_mem(100000000); check_mem(1000000000); check_mem(10000000000);}fn check_mem(bytes: usize) { let before = memory_stats().unwrap(); let _text = "x".repeat(bytes); let after = memory_stats().unwrap(); let physical_mem = after.physical_mem - before.physical_mem; let virtual_mem = after.virtual_mem - before.virtual_mem; println!( "{:>15} {:>15} {:>15}", bytes.separate_with_commas(), physical_mem.separate_with_commas(), virtual_mem.separate_with_commas() )}fn show_mem() { if let Some(usage) = memory_stats() { println!( "物理內存使用: {:>15}", usage.physical_mem.separate_with_commas() ); println!( "虛擬內存使用: {:>15}", usage.virtual_mem.separate_with_commas() ); } else { println!("Couldn't get the current memory usage :("); }}
把這個程序運行了3次,看看結果是否一致。
cargo run -q物理內存使用: 1,966,080虛擬內存使用: 3,338,240 字節 物理內存 虛擬內存 10,000 0 0 100,000 0 0 1,000,000 1,048,576 1,003,520 10,000,000 9,961,472 10,002,432 100,000,000 99,876,864 100,003,840 1,000,000,000 999,948,288 1,000,001,536 10,000,000,000 9,999,876,096 10,000,003,072cargo run -q物理內存使用: 1,966,080虛擬內存使用: 3,338,240 字節 物理內存 虛擬內存 10,000 0 0 100,000 0 0 1,000,000 1,048,576 1,003,520 10,000,000 9,961,472 10,002,432 100,000,000 99,876,864 100,003,840 1,000,000,000 999,817,216 1,000,001,536 10,000,000,000 9,999,876,096 10,000,003,072cargo run -q物理內存使用: 1,966,080虛擬內存使用: 3,338,240 字節 物理內存 虛擬內存 10,000 131,072 0 100,000 0 0 1,000,000 1,048,576 1,003,520 10,000,000 9,961,472 10,002,432 100,000,000 99,876,864 100,003,840 1,000,000,000 999,948,288 1,000,001,536 10,000,000,000 9,999,876,096 10,000,003,072
對于10,000和100,000字節,在兩次執行中得到0更改,并且在第三次運行中得到單個131,072更改。從1,000,000字節開始,結果在3次運行中相當一致,它們也表明已使用內存的變化類似于創建字符串的大小。
本文鏈接:http://www.tebozhan.com/showinfo-26-99644-0.html我們聊聊如何分析Rust進程使用了多少內存?
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 微服務開發時,接口不能對外暴露怎么辦?
下一篇: 云音樂2023年報前端大揭秘