Skip to content

Expose memory usage statistics to Rust via SnMalloc::memory_stats()#851

Open
jayakasadev wants to merge 2 commits into
microsoft:mainfrom
jayakasadev:rust-memory-stats
Open

Expose memory usage statistics to Rust via SnMalloc::memory_stats()#851
jayakasadev wants to merge 2 commits into
microsoft:mainfrom
jayakasadev:rust-memory-stats

Conversation

@jayakasadev
Copy link
Copy Markdown
Contributor

@jayakasadev jayakasadev commented May 27, 2026

Summary

  • Adds AllocStats { current_memory_usage, peak_memory_usage } to snmalloc-rs
  • Adds SnMalloc::memory_stats() -> AllocStats associated function
  • Adds FFI binding for sn_rust_statistics in snmalloc-sys

No C++ changes were required — sn_rust_statistics already existed in rust.cc and StatsRange counters are always active regardless of the stats build feature.

The returned values are OS-level memory reservation figures at slab/chunk granularity (tracked atomically by StatsRange), not the sum of individual live allocation sizes.

Usage

let stats = SnMalloc::memory_stats();
println!("current: {} bytes, peak: {} bytes",
    stats.current_memory_usage,
    stats.peak_memory_usage);

Test plan

  • cargo test --package snmalloc-rs — 7/7 tests pass including new test_memory_stats
  • test_memory_stats allocates 1 MiB, verifies current/peak are non-decreasing after allocation, and that peak never decreases after free

Wire up the existing `sn_rust_statistics` C export (already present in
rust.cc) to Rust. Adds an FFI binding in snmalloc-sys and a safe
`SnMalloc::memory_stats()` associated function in snmalloc-rs that
returns an `AllocStats` struct with current and peak OS-level memory
reservation figures tracked by StatsRange.

No C++ changes required — the backend counters are always active.
Copy link
Copy Markdown
Member

@mjp41 mjp41 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants