Last active
November 16, 2021 02:16
-
-
Save LewkyB/e462b963cdd2e943c1be03799c433001 to your computer and use it in GitHub Desktop.
test using tracemallloc https://docs.python.org/3/library/tracemalloc.html
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 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