While profiling memory on a C99-backed Python query matcher I maintain (Mongory, an in-memory MongoDB-style rule engine), tracemalloc told me compiling 1,000 matchers for a 500-item $in query took 9,457 B per instance on Python 3.14.5. Querying macOS malloc_zone_statistics around the same loop showed 142,317 B per instance, roughly 15x more RAM than Python's profiler reported.
The same gap showed up in Ruby (4.0.5) when checking GC.stat and ObjectSpace. If you profile or ship native C extensions in Python or Ruby, VM memory tools miss C heap allocations silently unless both your extension and your benchmark account for them.
Why Python and Ruby profilers miss C heap
Python's tracemalloc only installs hooks into Python's own allocator domains (PYMEM_DOMAIN_RAW, PYMEM_DOMAIN_MEM, and PYMEM_DOMAIN_OBJ). Objects and buffers created with PyObject_* or PyMem_* appear cleanly. When a wrapped C library allocates AST nodes, hash tables, or scratch buffers using libc malloc or calloc directly, those calls skip Python's hooks completely, so tracemalloc reports only the small Python wrapper object sitting on top.
Ruby's GC.stat(:heap_live_slots) and GC.stat(:total_allocated_objects) count Ruby RVALUE slots inside Ruby's GC heaps. ObjectSpace.memsize_of(obj) can add external C allocations to that total, but only if the extension fills in .dsize on its rb_data_type_t struct descriptor and manually walks the native buffers it owns. Leaving .dsize = NULL compiles without a warning and tells Ruby the wrapper consumes nothing beyond one object slot. Worse, Ruby's GC triggers largely from slot growth and tracked bytes, so untracked C allocations can grow well past what the VM thinks the process uses.
Measuring the real bytes from outside the VM
To benchmark native extensions accurately, pair VM heap metrics with the OS allocator and process RSS. On macOS (arm64), Python's standard library gives you both through ctypes and resource:
import ctypes
import ctypes.util
import resource
class MallocStatistics(ctypes.Structure):
_fields_ = [
("blocks_in_use", ctypes.c_uint),
("size_in_use", ctypes.c_size_t),
("max_size_in_use", ctypes.c_size_t),
("size_allocated", ctypes.c_size_t),
]
libc = ctypes.CDLL(ctypes.util.find_library("c"))
libc.malloc_zone_statistics.argtypes = [ctypes.c_void_p, ctypes.POINTER(MallocStatistics)]
libc.malloc_zone_statistics.restype = None
def malloc_in_use() -> int:
st = MallocStatistics()
libc.malloc_zone_statistics(None, ctypes.byref(st))
return int(st.size_in_use)
def max_rss_bytes() -> int:
return int(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
In Ruby 4.0, fiddle is no longer shipped in default gems, so reading malloc_zone_statistics without adding external gem dependencies takes a 23-line C extension probe:
#include <ruby.h>
#include <malloc/malloc.h>
#include <sys/resource.h>
static VALUE rb_malloc_in_use(VALUE self) {
malloc_statistics_t st;
malloc_zone_statistics(NULL, &st);
return ULL2NUM((unsigned long long)st.size_in_use);
}
static VALUE rb_max_rss(VALUE self) {
struct rusage ru;
if (getrusage(RUSAGE_SELF, &ru) != 0) {
rb_sys_fail("getrusage");
}
return LL2NUM((long long)ru.ru_maxrss);
}
void Init_rb_malloc_probe(void) {
VALUE mod = rb_define_module("MallocProbe");
rb_define_singleton_method(mod, "malloc_in_use", rb_malloc_in_use, 0);
rb_define_singleton_method(mod, "max_rss", rb_max_rss, 0);
}
On Linux with glibc 2.33+, mallinfo2().uordblks reports live malloc bytes and /proc/self/status (VmRSS and VmHWM) tracks RSS. Keep in mind that ru_maxrss returns kilobytes on Linux and bytes on macOS.
A real case: arena pools vs pure-VM interpreters
When I wired those probes into a memory benchmark on an Apple M3 (macOS arm64, Python 3.14.5, Ruby 4.0.5) holding 1,000 compiled matcher instances alive, the numbers exposed what VM tools had been hiding:
| Query (1,000 instances retained) | Python tracemalloc
|
Python malloc_zone_statistics
|
Ruby malloc_zone_statistics (+ slots) |
|---|---|---|---|
Simple (age >= 18) |
1,171 B |
5,646 B |
4,687 B (5 slots) |
Nested (profile.city == "taipei" + 2 ops) |
1,210 B |
9,740 B |
8,811 B (5 slots) |
500-item $in hash lookup |
9,457 B |
142,317 B |
137,372 B (6 slots) |
The reason a trivial age >= 18 rule takes roughly 5 KB in C goes back to arena sizing. Each compiled rule in that engine allocates two 2 KB bump-allocated arena pools: one long-lived arena for the compiled AST and string lookup tables, and one reusable scratch arena so evaluation can reset scratch state in O(1) without calling malloc per record. Add small hash maps and thread locks in the Python/Ruby wrapper, and you get the 4.7 KB to 5.6 KB floor. In pure C without binding overhead, the same simple rule costs 2,256 B with its own pool, or 520 B if multiple rules share one arena.
Comparing that architecture against pure-VM rule libraries in Python (mongoquery 1.4.3) and Ruby (mongoid 9.1.3) shows where C arenas help and where they can burn you.
On startup and 10,000-record match passes, pre-compiled C arenas slash VM object churn and framework overhead. Requiring the C-backed Ruby gem (141.7 KB binary, 0 runtime deps) adds +0.8 MiB RSS and +1,403 Ruby slots, then evaluates 10,000 records while allocating only 2 to 7 Ruby objects (0.0 to 0.1 KiB C alloc) inside a GC.disable pass. By contrast, require 'mongoid' loads 19 gems (+47.3 MiB RSS, +91,286 slots), wrapping 10,000 plain Ruby hashes in Mongoid::Document costs another +2,361.6 KiB and +120,338 slots, and evaluating 10,000 records allocates 113,202 Ruby objects on a simple numeric check, 310,002 objects (+10.2 MiB malloc) on regex, and 4,796,168 Ruby objects (+5.6 MiB malloc) on a 500-item $in.
Python tells a sneakier story. mongoquery (+0.2 MiB import RSS) looks nearly free in both tracemalloc and malloc_zone_statistics: 64 B to 92 B retained per rule (it just keeps the raw dict), and 2.3 KiB to 3.7 KiB peak during a 10,000-record scan because CPython's reference counting frees each per-record temporary list and generator before the next record runs. The RAM ceiling stays flat while CPU time climbs to 9x to 24x slower on normal queries and 2,314x slower on a 500-item $in (258,170 ns/rec vs 111.6 ns/rec).
The trade-off flips completely if you cache massive numbers of tiny distinct rules. Holding 500,000 distinct compiled rules at ~5 KB each eats ~2.5 GB of native C heap that neither tracemalloc nor GC.stat sees coming before the OS OOM-killer terminates the worker. Pure garbage-collected ports of the same query spec avoid that 2 KB chunk floor (640 B in Go and 834 B in JS for the simple rule), and for one-off queries over small lists in Python, a tiny 327-line interpreter like mongoquery or a plain if statement is simpler and lighter on startup.
How to make your own C extension visible
If you are building a Python or Ruby extension around native arenas or buffers, you can make those bytes visible to the runtime instead of hiding them.
In Ruby, implement .dsize on rb_data_type_t so ObjectSpace.memsize_of reports total native ownership, and notify Ruby's GC whenever the native allocation grows or shrinks:
static size_t my_ext_dsize(const void *ptr) {
const my_wrapper_t *w = (const my_wrapper_t *)ptr;
if (!w) return 0;
return sizeof(my_wrapper_t) + my_arena_bytes(w);
}
static const rb_data_type_t my_ext_type = {
.wrap_struct_name = "my_ext",
.function = {
.dmark = my_ext_mark,
.dfree = my_ext_free,
.dsize = my_ext_dsize,
},
.flags = RUBY_TYPED_FREE_IMMEDIATELY,
};
/* Call rb_gc_adjust_memory_usage(bytes) after allocating or freeing large chunks. */
For ad-hoc allocations outside a fixed C library pool, calling ruby_xmalloc and ruby_xfree updates Ruby's malloc counters automatically. Be careful before routing a general-purpose C library through ruby_xmalloc, though: it requires the GVL and raises NoMemoryError via longjmp on OOM, which bypasses mutex unlocks and NULL-based error cleanup inside C code. When wrapping a lock-holding or OOM-safe C library, keeping libc malloc alongside .dsize and rb_gc_adjust_memory_usage is safer.
In Python, if the C library accepts custom allocator callbacks, wire it to PyMem_RawMalloc, PyMem_RawCalloc, and PyMem_RawFree (and free every pointer from that allocator with PyMem_RawFree, never libc free, or tracemalloc will crash on teardown). Those functions belong to Python's raw allocator domain, do not require holding the GIL, return NULL on OOM, and feed allocation events into tracemalloc. Adding __sizeof__ on the wrapper class exposes total native pool size to sys.getsizeof as well.
After wiring both fixes into the query matcher bindings, tracemalloc on Python 3.14.5 jumped from 9,457 B to 141,137 B per 500-item $in instance (97.8% of the 144,364 B reported by malloc_zone_statistics in the same traced run), and sys.getsizeof reported 4,408 B (simple), 8,504 B (nested), and 131,384 B (500-item $in). On Ruby 4.0.5, ObjectSpace.memsize_of went from reporting only the Ruby wrapper slot to 4,360 B, 8,456 B, and 131,336 B without adding any per-record allocations on the hot path. When wrapping an external C library whose allocator cannot be swapped cleanly, measure its malloc delta with malloc_zone_statistics or mallinfo2 in your test suite and document the per-instance C overhead explicitly.
Four habits keep extension memory benchmarks honest:
- Measure both VM counters (
tracemalloc,GC.stat) and OS counters (malloc_zone_statisticsormallinfo2, plusru_maxrssacross fresh subprocesses). - Measure compiled state by retaining 1,000 live instances in an array before forcing GC, so small uninstrumented sub-allocations cannot hide in noise.
- Measure hot-path allocation rate inside
GC.disable(Ruby) orgc.disable()passes, and inspect CPU latency alongside peak memory so CPython refcounting does not disguise per-record churn. - Count wrapper conversions (
Mongoid::Document, BSON documents) when comparing libraries that cannot read plain dicts or hashes directly.
The full cross-language memory and footprint benchmark tables behind these numbers live on Mongory Central.
Top comments (0)