Skip to main content

dhat_drop_in/
dhat_drop_in.rs

1//! dhat-rs drop-in swap demo.
2//!
3//! Compare to dhat-rs's introductory example: change only the
4//! import line and this code runs against mod-alloc.
5//!
6//! Run with:
7//!   cargo run --release --features dhat-compat --example dhat_drop_in
8//!
9//! Drops `dhat-heap.json` in the current working directory on
10//! exit. Open it in `dh_view.html` (shipped with Valgrind) to
11//! inspect the per-call-site report.
12
13#[cfg(feature = "dhat-compat")]
14use mod_alloc::dhat_compat as dhat;
15
16#[cfg(feature = "dhat-compat")]
17#[global_allocator]
18static ALLOC: dhat::Alloc = dhat::Alloc;
19
20#[cfg(feature = "dhat-compat")]
21#[inline(never)]
22fn alloc_small() {
23    let v: Vec<u8> = Vec::with_capacity(64);
24    std::hint::black_box(&v);
25}
26
27#[cfg(feature = "dhat-compat")]
28#[inline(never)]
29fn alloc_medium() {
30    let v: Vec<u8> = Vec::with_capacity(1024);
31    std::hint::black_box(&v);
32}
33
34#[cfg(feature = "dhat-compat")]
35fn main() {
36    let _profiler = dhat::Profiler::new_heap();
37
38    for _ in 0..500 {
39        alloc_small();
40    }
41    for _ in 0..100 {
42        alloc_medium();
43    }
44
45    let stats = dhat::HeapStats::get();
46    println!(
47        "total_blocks: {}, total_bytes: {}, max_bytes: {}, curr_blocks: {}",
48        stats.total_blocks, stats.total_bytes, stats.max_bytes, stats.curr_blocks,
49    );
50    println!("_profiler drops at end of main → writes dhat-heap.json");
51}
52
53#[cfg(not(feature = "dhat-compat"))]
54fn main() {
55    eprintln!(
56        "this example requires the `dhat-compat` feature; run with \
57         `cargo run --features dhat-compat --example dhat_drop_in`"
58    );
59}