Skip to content

Instantly share code, notes, and snippets.

@Suor
Created January 15, 2021 12:35
Show Gist options
  • Save Suor/50d8d24f3ef969e8808e1e0d7af04f06 to your computer and use it in GitHub Desktop.
Save Suor/50d8d24f3ef969e8808e1e0d7af04f06 to your computer and use it in GitHub Desktop.
Get python structure total memory size
def getsize(obj):
import sys
from types import ModuleType, FunctionType
from gc import get_referents
BLACKLIST = type, ModuleType, FunctionType
if isinstance(obj, BLACKLIST):
raise TypeError('getsize() does not take argument of type: '+ str(type(obj)))
seen_ids = set()
size = 0
objects = [obj]
while objects:
need_referents = []
for obj in objects:
if not isinstance(obj, BLACKLIST) and id(obj) not in seen_ids:
seen_ids.add(id(obj))
size += sys.getsizeof(obj)
need_referents.append(obj)
objects = get_referents(*need_referents)
return size
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment