Skip to content

Instantly share code, notes, and snippets.

@rawlik
Created August 16, 2023 08:55
Show Gist options
  • Save rawlik/4bd0a7538eb1a1df6053a4fba311e2f8 to your computer and use it in GitHub Desktop.
Save rawlik/4bd0a7538eb1a1df6053a4fba311e2f8 to your computer and use it in GitHub Desktop.
Show the largest variables by memory use in python.
def sizeof_fmt(num, suffix='B'):
''' by Fred Cirera, https://stackoverflow.com/a/1094933/1870254, modified'''
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f %s%s" % (num, 'Yi', suffix)
def numpysizeof(o):
if "nbytes" in dir(o):
if type(o.nbytes) is int:
return o.nbytes
return sys.getsizeof(o)
for name, size in sorted(((name, numpysizeof(value)) for name, value in list(
locals().items())), key= lambda x: -x[1])[:10]:
print("{:>30}: {:>8}".format(name, sizeof_fmt(size)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment