Skip to content

Instantly share code, notes, and snippets.

@prerakmody
Created July 3, 2022 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prerakmody/ad6881ab2855af7f0f34770b33cd9391 to your computer and use it in GitHub Desktop.
Save prerakmody/ad6881ab2855af7f0f34770b33cd9391 to your computer and use it in GitHub Desktop.
Object Size in python
import gc
import sys
import humanize # pip install humanize
def actualsize(input_obj):
# https://towardsdatascience.com/the-strange-size-of-python-objects-in-memory-ce87bdfbb97f
memory_size = 0
ids = set()
objects = [input_obj]
while objects:
new = []
for obj in objects:
if id(obj) not in ids:
ids.add(id(obj))
memory_size += sys.getsizeof(obj) # Return the size of an object in bytes
new.append(obj)
objects = gc.get_referents(*new)
return humanize.naturalsize(memory_size)
actualsize([1,2,3,[4,5]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment