Skip to main content

dhat_json/
dhat_json.rs

1//! DHAT-compatible JSON output demo.
2//!
3//! Run with:
4//!   cargo run --release --features dhat-compat --example dhat_json
5//!
6//! Or with symbolicated frames in the JSON:
7//!   cargo run --release --features symbolicate,dhat-compat --example dhat_json
8//!
9//! Drops a `dhat-heap.json` file in the current working directory.
10//! Load that file in `dh_view.html` (shipped with Valgrind) to
11//! inspect the per-call-site report visually.
12
13#[cfg(feature = "dhat-compat")]
14#[global_allocator]
15static GLOBAL: mod_alloc::ModAlloc = mod_alloc::ModAlloc::new();
16
17#[cfg(feature = "dhat-compat")]
18#[inline(never)]
19fn alloc_small() {
20    let v: Vec<u8> = Vec::with_capacity(64);
21    std::hint::black_box(&v);
22}
23
24#[cfg(feature = "dhat-compat")]
25#[inline(never)]
26fn alloc_medium() {
27    let v: Vec<u8> = Vec::with_capacity(1024);
28    std::hint::black_box(&v);
29}
30
31#[cfg(feature = "dhat-compat")]
32#[inline(never)]
33fn alloc_large() {
34    let v: Vec<u8> = Vec::with_capacity(64 * 1024);
35    std::hint::black_box(&v);
36}
37
38#[cfg(feature = "dhat-compat")]
39fn main() -> std::io::Result<()> {
40    for _ in 0..500 {
41        alloc_small();
42    }
43    for _ in 0..100 {
44        alloc_medium();
45    }
46    for _ in 0..10 {
47        alloc_large();
48    }
49
50    let snap = GLOBAL.snapshot();
51    println!(
52        "captured {} allocations, {} total bytes, peak {} bytes",
53        snap.alloc_count, snap.total_bytes, snap.peak_bytes
54    );
55
56    let path = std::path::Path::new("dhat-heap.json");
57    GLOBAL.write_dhat_json(path)?;
58
59    let abs = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
60    println!("wrote {}", abs.display());
61    println!("open it in dh_view.html to inspect.");
62    Ok(())
63}
64
65#[cfg(not(feature = "dhat-compat"))]
66fn main() {
67    eprintln!(
68        "this example requires the `dhat-compat` feature; run with \
69         `cargo run --features dhat-compat --example dhat_json`"
70    );
71}