r/Python • • 9h ago

Discussion tracemalloc said 9.5 KB. macOS said 142 KB: why Python profilers miss C heap

0 Upvotes

tracemalloc.get_traced_memory() reported 9,457 B per compiled 500-item $in rule on Python 3.14.5. Calling macOS malloc_zone_statistics around the same 1,000-instance loop reported 142,317 B per instance, 15x more RAM than Python admitted existed.

Built-in Python profilers stay blind to C heap unless both your benchmark and your C extension cross the allocator boundary.

Why tracemalloc misses C heap

Python's tracemalloc hooks PYMEM_DOMAIN_RAW, PYMEM_DOMAIN_MEM, and PYMEM_DOMAIN_OBJ (PyObject_* and PyMem_*). Direct libc malloc or calloc calls inside a wrapped C library skip all three hooks, leaving only the thin Python wrapper shell visible.

sys.getsizeof(obj) has the same blind spot unless the extension implements __sizeof__ to add up the native structs and pools behind the PyObject.

Measuring real bytes outside the VM

On macOS (arm64), Python's standard library can read both live native heap and process RSS via ctypes and resource:

import ctypes, ctypes.util, 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)]

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)

On Linux (glibc 2.33+), use mallinfo2().uordblks for live malloc bytes and /proc/self/status (VmRSS / VmHWM), noting that ru_maxrss returns KiB on Linux and bytes on macOS.

Where the hidden 142 KB went (and when C arenas lose)

Holding 1,000 compiled rules alive on an Apple M3 (macOS arm64) exposed the gap:

Rule (1,000 retained)Python tracemallocReal malloc (size_in_use)
Simple (age >= 18)1,171 B5,646 B
Nested (profile.city + 2 ops)1,210 B9,740 B
500-item $in hash9,457 B142,317 B

Each compiled object allocates two 2 KB bump-allocated arena pools (one for the AST and lookup tables, one reusable scratch pool for zero-malloc matching) plus binding structs, setting a ~5 KB floor per rule (pure C uses 2,256 B standalone or 520 B with a shared arena).

Comparing against a pure-Python peer (mongoquery 1.4.3, +0.2 MiB RSS) shows the trade-off runs both ways:

  • mongoquery retains only 64 B to 92 B per rule and peaks at 2.3 KiB to 3.7 KiB because CPython refcounting frees temporaries right away, shifting the cost into 9x to 2,314x higher CPU time (258,170 ns/rec vs 111.6 ns/rec).
  • Caching 500,000 tiny distinct rules flips the win around: ~5 KB per rule eats ~2.5 GB of hidden C heap until OOM-kill. Pure GC ports avoid the 2 KB C chunk floor (640 B in Go, 834 B in JS), and one-off queries over small lists are cheaper with plain Python.

Fixing it with PyMem_RawMalloc and __sizeof__

Wiring the C library's allocator callbacks to PyMem_RawMalloc and PyMem_RawFree routed every C arena into tracemalloc, and adding __sizeof__ exposed native pools to sys.getsizeof.

Two practical constraints:

  1. PyMem_RawMalloc / PyMem_RawFree are GIL-free and return NULL on OOM, so they don't break a C library's NULL-checked OOM paths (unlike PyMem_Malloc, which requires the GIL).
  2. Every pointer allocated through that hook must be freed with PyMem_RawFree, never libc free, or tracemalloc crashes on teardown.

After wiring it up:

  • tracemalloc jumped from 9,457 B to 141,137 B per 500-item $in instance (97.8% of the 144,364 B traced malloc_zone_statistics total).
  • sys.getsizeof reported 4,408 B, 8,504 B, and 131,384 B.
  • Matching speed stayed flat (89.2 ns/rec vs 86.8 ns/rec).

If you maintain Python C extensions with custom allocators or arena pools, do you wire them through PyMem_RawMalloc or test native heap (mallinfo2 / malloc_zone_statistics) in CI?


r/Python • • 23h ago

Showcase Showcase Thread

17 Upvotes

Post all of your code/projects/showcases/AI slop here.

Recycles once a month.


r/Python • • 16h ago

Daily Thread Saturday Daily Thread: Resource Request and Sharing! Daily Thread

11 Upvotes

Weekly Thread: Resource Request and Sharing 📚

Stumbled upon a useful Python resource? Or are you looking for a guide on a specific topic? Welcome to the Resource Request and Sharing thread!

How it Works:

  1. Request: Can't find a resource on a particular topic? Ask here!
  2. Share: Found something useful? Share it with the community.
  3. Review: Give or get opinions on Python resources you've used.

Guidelines:

  • Please include the type of resource (e.g., book, video, article) and the topic.
  • Always be respectful when reviewing someone else's shared resource.

Example Shares:

  1. Book: "Fluent Python" - Great for understanding Pythonic idioms.
  2. Video: Python Data Structures - Excellent overview of Python's built-in data structures.
  3. Article: Understanding Python Decorators - A deep dive into decorators.

Example Requests:

  1. Looking for: Video tutorials on web scraping with Python.
  2. Need: Book recommendations for Python machine learning.

Share the knowledge, enrich the community. Happy learning! 🌟