Rust runtime: get total memory currently being used

In my Rust/wasm32 app, I want a real time display of how much memory is being used. Do I need to track this manually, or is there a way to directly query the Rust runtime to get how much stack + heap is being used?

I don't think that Rust's commitment to zero-cost abstractions would allow tracking how much memory is used by default. You will have to track this manually. This can be done for the heap by writing an global allocator that keeps track of how much data is currently allocated and then defers allocation to some other allocator.
For the stack, I'm not sure what you can do.


I would prefer to not intercept on the global allocator.

Suppose I'm willing to accept an approximate answer i.e. if the true memory usage is N, I'm okay with some value (N -> 2N).

Is there some other hack that can get me an approximate value?

Your program could use memory buffer, but that is making a new global allocator.

Benefits of using a memory buffers
Less context switching (syscalls to alloc/dealloc memory) - making you program faster - sometimes a lot faster.

Con: More memory than necessary/needed are allocated, but you can make it possible to switch between deallocation algorithms at runtime/compile time. Each algorithm implements a deallocation policy.

Pro tip: If possible, put one memory buffer object/item within the same page (usually 4096 bytes), so the kernel doesn't need to work with 2 pages.

1 Like

Coming from the JVM, I was expecting there to be a builtin function -- but I guess it makes sense -- this is the cost of 0 cost abstractions.

On Linux there's a way of asking the OS, which the Prometheus crate uses. With the jemallocator crate the allocator can be asked via jemalloc-ctl. Under WASM, there might be a memory usage call but I'm not familiar enough with what WASM provides.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.