memory-stats

A cross-platform Rust crate that reads a process's physical and virtual memory usage with a single function call.

Library
Cargo
v1.2.0
43stars
MIT OR Apache-2.0

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum.How we score it →
22/100Needs Attention
Development Activity0
Maintenance0
Community20
Maturity56
Momentum12

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation.How we score it →
60/100Good
Architecture78
Code Quality65
Innovation38
Learning Curve60

memory-stats is a small, dependency-light Rust crate for querying how much memory the current process is using. A single memory_stats() call returns both “physical” memory (Resident Set Size on Linux/macOS, Working Set on Windows) and “virtual” memory (Virtual Size on Linux/macOS, Pagefile Usage on Windows) as a plain MemoryStats struct, with no OS-specific code required in the caller.

Under the hood it dispatches to a platform-specific backend at compile time: /proc/self/smaps (falling back to the faster but less precise /proc/self/statm) on Linux and Android, task_info via libc on macOS/iOS, GetProcessMemoryInfo via windows-sys on Windows, and an equivalent libc path on FreeBSD. Unsupported targets get a safe no-op that returns None rather than failing to compile.

It’s aimed at profiling and diagnostics use cases — printing memory usage in benchmarks, logging it in long-running services, or feeding it into monitoring output — where pulling in a full profiling framework would be overkill. An optional serde feature adds Serialize/Deserialize on the result struct, and an always_use_statm feature trades Linux accuracy for speed.

What You Get

  • A single memory_stats() function returning Option<MemoryStats> with physical_mem and virtual_mem in bytes
  • Platform backends for Windows (via windows-sys), Linux/Android (/proc/self/smaps with /proc/self/statm fallback), macOS/iOS, and FreeBSD
  • An always_use_statm feature flag to trade Linux measurement accuracy for lower overhead
  • An optional serde feature that derives Serialize/Deserialize on MemoryStats for logging or shipping the metrics elsewhere
  • Graceful None return on unsupported targets instead of a compile failure

Common Use Cases

  • Printing before/after memory usage in Rust benchmarks and micro-benchmarking harnesses
  • Logging periodic memory snapshots inside long-running services or daemons
  • Feeding physical/virtual memory readings into a custom metrics or telemetry pipeline via the serde feature
  • Debugging suspected memory leaks by sampling memory_stats() around suspect code paths
  • Cross-platform CLI tools that want to self-report resource usage without pulling in a full profiler

Under The Hood

Architecture The crate uses a single conditional-compilation seam in lib.rs: a mod platform is aliased via #[path = "..."] to one of windows.rs, linux.rs, darwin.rs, or freebsd.rs based on target_os, plus an inline no-op fallback module for anything else. Every backend exposes the same memory_stats() -> Option<MemoryStats> signature, so lib.rs itself contains no branching logic beyond the module selection — the public API is a thin, uniform wrapper over whichever backend got compiled in. The Linux backend is the most involved: it caches (via AtomicBools) whether /proc/self/smaps is available on first call, then either parses smaps line-by-line for accurate size/RSS or falls back to the cheaper /proc/self/statm, converting page counts using a cached page size.

Tech Stack Pure Rust, edition 2021, with a deliberately minimal dependency footprint: serde (optional, derive feature) for the opt-in serialization feature, windows-sys 0.52 scoped to cfg(target_os = "windows") for the GetProcessMemoryInfo FFI call, and libc 0.2 scoped to the Unix-family targets. There’s no async runtime, web framework, or database involved — this is a systems-level utility crate. rustfmt.toml and deny.toml (cargo-deny, for license/dependency auditing) indicate a formatting and supply-chain hygiene setup alongside the code itself.

Code Quality There is one integration test (tests/allocate_4mb_of_memory.rs) that allocates and fills 4MB of memory and asserts the reported virtual/physical usage increases accordingly across whatever platform CI runs on — a real, behavioral test rather than a mock. There are no unit tests inside the source modules themselves (e.g. the scan_int smaps/statm parser has no dedicated test). Error handling is consistently Option-based with no panics on the fallible paths; the one unsafe block (the Windows FFI call) carries an explicit // SAFETY comment justifying it. CI (.github/workflows/ci.yml) runs the test suite across a matrix of Ubuntu, Windows, and macOS on both stable and nightly Rust, with rustfmt and clippy added on the nightly leg.

Code Quality (continued: API Design) The public surface is intentionally tiny — one function, one struct, two documented fields — which keeps the barrier to adoption very low: add the crate, call memory_stats(), done. Doc comments on lib.rs double as the crate-level README content (mirrored via #[doc]), explaining exactly what each metric maps to on each OS, and the crate’s own doctest exercises the example from the docs. The tradeoff is that callers get no control over which backend runs (aside from the always_use_statm feature) and no finer-grained metrics (e.g. no heap-only breakdown) — appropriate for its stated scope as a lightweight read, not a full profiler.

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers

Search