1#[cfg(feature = "backtraces")]
12#[global_allocator]
13static GLOBAL: mod_alloc::ModAlloc = mod_alloc::ModAlloc::new();
14
15#[cfg(feature = "backtraces")]
16#[inline(never)]
17fn alloc_small() {
18 let v: Vec<u8> = Vec::with_capacity(64);
19 std::hint::black_box(&v);
20}
21
22#[cfg(feature = "backtraces")]
23#[inline(never)]
24fn alloc_medium() {
25 let v: Vec<u8> = Vec::with_capacity(1024);
26 std::hint::black_box(&v);
27}
28
29#[cfg(feature = "backtraces")]
30#[inline(never)]
31fn alloc_large() {
32 let v: Vec<u8> = Vec::with_capacity(64 * 1024);
33 std::hint::black_box(&v);
34}
35
36#[cfg(feature = "backtraces")]
37fn main() {
38 for _ in 0..1_000 {
39 alloc_small();
40 }
41 for _ in 0..100 {
42 alloc_medium();
43 }
44 for _ in 0..10 {
45 alloc_large();
46 }
47
48 let snap = GLOBAL.snapshot();
49 println!("Process-wide snapshot:");
50 println!(" alloc_count: {}", snap.alloc_count);
51 println!(" total_bytes: {}", snap.total_bytes);
52 println!(" current_bytes: {}", snap.current_bytes);
53 println!(" peak_bytes: {}", snap.peak_bytes);
54 println!();
55
56 let mut sites = GLOBAL.call_sites();
57 sites.sort_by_key(|s| std::cmp::Reverse(s.total_bytes));
58
59 println!("Top 10 call sites by total bytes:");
60 println!(
61 "{:>10} {:>14} {:>4} {:>18}",
62 "count", "total_bytes", "frm", "top frame"
63 );
64 for (rank, site) in sites.iter().take(10).enumerate() {
65 println!(
66 "{rank:>2}: {count:>6} {bytes:>14} {frm:>4} {top:#018x}",
67 rank = rank,
68 count = site.count,
69 bytes = site.total_bytes,
70 frm = site.frame_count,
71 top = site.frames[0],
72 );
73 }
74}
75
76#[cfg(not(feature = "backtraces"))]
77fn main() {
78 eprintln!(
79 "this example requires the `backtraces` feature; run with \
80 `cargo run --features backtraces --example backtraces`"
81 );
82}