What is the sys.getsizeof() function, and what are its limitations for measuring memory usage?
Short answer
sys.getsizeof(obj) returns the memory size in bytes of the object itself, but not the objects it references -- a list of large strings might report a small size for the list container while the actual strings it points to consume much more memory elsewhere.
Advertisement
AModel answer
sys.getsizeof(obj) returns the memory size in bytes of the object itself, but not the objects it references -- a list of large strings might report a small size for the list container while the actual strings it points to consume much more memory elsewhere. To measure deep memory usage, you need to recursively sum referenced objects (e.g., with a library like pympler) or use sys.getsizeof carefully with a visited-set to avoid double-counting cycles.
import sys
small_list = [1, 2, 3]
print(sys.getsizeof(small_list)) # size of the list structure only
print(sys.getsizeof(small_list) + sum(sys.getsizeof(x) for x in small_list)) # closer to real usageReal-world example
A memory-profiling script mistakenly concludes a nested data structure is small because it only calls getsizeof on the outer container, missing the megabytes referenced by inner lists.
Likely follow-ups
- How does pympler.asizeof compute deep sizes?
- Why doesn't getsizeof recurse by default?
Related topics