我們聊聊如何分析Rust進程使用了多少內(nèi)存?
在篇文章中,我們使用memory-stats crate來報告和分析Rust進程使用了多少內(nèi)存,它依賴于操作系統(tǒng)的內(nèi)存計算。
使用以下命令創(chuàng)建一個Rust新項目:
cargo new memory-stats-example
加入以下依賴項:
[dependencies]
memory-stats = { version = "1.1.0", features = ["always_use_statm"] }
thousands = "0.2.0"
基本上我們分析兩種內(nèi)存:
- 物理內(nèi)存:對應于Linux和MacOS上的常駐內(nèi)存集大小和Windows上的工作內(nèi)存集大小。
- 虛擬內(nèi)存:對應于Linux和MacOS上的虛擬內(nèi)存大小和Windows上的頁面內(nèi)存使用情況。
在我們的例子中,創(chuàng)建了包含許多字符的變量,在創(chuàng)建變量之前和之后,打印內(nèi)存差異。
在src/main.rs文件中寫入以下代碼:
use memory_stats::memory_stats;
use thousands::Separable;
fn main() {
show_mem();
println!(" 字節(jié) 物理內(nèi)存 虛擬內(nèi)存 ");
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!(
"物理內(nèi)存使用: {:>15}",
usage.physical_mem.separate_with_commas()
);
println!(
"虛擬內(nèi)存使用: {:>15}",
usage.virtual_mem.separate_with_commas()
);
} else {
println!("Couldn't get the current memory usage :(");
}
}
把這個程序運行了3次,看看結(jié)果是否一致。
cargo run -q
物理內(nèi)存使用: 1,966,080
虛擬內(nèi)存使用: 3,338,240
字節(jié) 物理內(nèi)存 虛擬內(nèi)存
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,072
cargo run -q
物理內(nèi)存使用: 1,966,080
虛擬內(nèi)存使用: 3,338,240
字節(jié) 物理內(nèi)存 虛擬內(nèi)存
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,072
cargo run -q
物理內(nèi)存使用: 1,966,080
虛擬內(nèi)存使用: 3,338,240
字節(jié) 物理內(nèi)存 虛擬內(nèi)存
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字節(jié),在兩次執(zhí)行中得到0更改,并且在第三次運行中得到單個131,072更改。從1,000,000字節(jié)開始,結(jié)果在3次運行中相當一致,它們也表明已使用內(nèi)存的變化類似于創(chuàng)建字符串的大小。