Skip to content

Instantly share code, notes, and snippets.

@LewkyB
Last active November 16, 2021 02:16
Show Gist options
  • Save LewkyB/e462b963cdd2e943c1be03799c433001 to your computer and use it in GitHub Desktop.
Save LewkyB/e462b963cdd2e943c1be03799c433001 to your computer and use it in GitHub Desktop.
import linecache
import os
import tracemalloc
def display_top(snapshot, key_type='lineno', limit=10):
snapshot = snapshot.filter_traces((
tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
tracemalloc.Filter(False, "<unknown>"),
))
top_stats = snapshot.statistics(key_type)
print("Top %s lines" % limit)
for index, stat in enumerate(top_stats[:limit], 1):
frame = stat.traceback[0]
print("#%s: %s:%s: %.1f KiB"
% (index, frame.filename, frame.lineno, stat.size / 1024))
line = linecache.getline(frame.filename, frame.lineno).strip()
if line:
print(' %s' % line)
other = top_stats[limit:]
if other:
size = sum(stat.size for stat in other)
print("%s other: %.1f KiB" % (len(other), size / 1024))
total = sum(stat.size for stat in top_stats)
print("Total allocated size: %.1f KiB" % (total / 1024))
tracemalloc.start()
# ... run your application ...
a = []
counter = 0
while counter != 1000:
a.append(' ' * 10**6)
print(len(a))
counter += 1
snapshot = tracemalloc.take_snapshot()
display_top(snapshot)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment