How to measure function memory with sys.getsizeof in Python

Measure the memory footprint of Python functions (user-defined and built-in) using sys.getsizeof.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 13 views 0 copies

Python code

13 lines
Python 3.9+
import sys

def sample_function(a, b, c):
    return a + b - c

def measure_function_memory(func):
    size = sys.getsizeof(func)
    print(f"Memory size of {func.__name__}: {size} bytes")

if __name__ == "__main__":
    measure_function_memory(sample_function)
    measure_function_memory(print)
    measure_function_memory(len)

Output

stdout
Memory size of sample_function: 144 bytes
Memory size of print: 72 bytes
Memory size of len: 72 bytes

How it works

sys.getsizeof returns the size of the object in bytes, including only the object itself, not referenced objects. For user-defined functions, the size includes the code object and metadata; built-ins like print and len are typically smaller. This is a diagnostic tool, not a precise memory profiler for the function's entire closure or referenced data.

Common mistakes

  • Assuming getsizeof includes referenced objects (it doesn't by default).
  • Measuring the function call result instead of the function object (e.g., `sys.getsizeof(func(...))`).
  • Comparing sizes across Python versions or interpreters, as they vary.

Variations

  1. Use `sys.getsizeof(func, default=0)` to avoid TypeError for objects without size info.
  2. Use `tracemalloc` for deeper memory analysis of function execution.

Real-world use cases

  • Debugging why a Python process uses more memory than expected by checking object sizes.
  • Estimating overhead when caching functions or storing them in data structures.
  • Profiling memory usage differences between built-in and custom functions in a performance audit.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.