Created
July 3, 2022 08:32
-
-
Save prerakmody/ad6881ab2855af7f0f34770b33cd9391 to your computer and use it in GitHub Desktop.
Object Size in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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