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.
Python code
13 linesimport 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
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
- Use `sys.getsizeof(func, default=0)` to avoid TypeError for objects without size info.
- 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
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.