Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import linecache
- import os
- import tracemalloc
- def create_pretty_stats(stats, key_type='lineno', limit=10):
- stats_list = sorted([stat for stat in stats], key=lambda k: k.size, reverse=True)
- stats_lines = []
- for index, stat in enumerate(stats_list[:limit], 1):
- frame = stat.traceback[0]
- filename = os.sep.join(frame.filename.split(os.sep)[-2:])
- stats_lines.append("#%s: %s:%s: %.1f KiB"
- % (index, filename, frame.lineno, stat.size / 1024))
- line = linecache.getline(frame.filename, frame.lineno).strip()
- if line:
- stats_lines.append(' %s' % line)
- other = stats[limit:]
- if other:
- size = sum(stat.size for stat in other)
- stats_lines.append("%s other: %.1f KiB" % (len(other), size / 1024))
- total = sum(stat.size for stat in stats_list)
- stats_lines.append("Total allocated size: %.1f KiB" % (total / 1024))
- return stats_lines
- # traces that should not be displayed
- snapshot_filter_traces = (
- tracemalloc.Filter(False, "<frozen importlib._bootstrap_external>"),
- tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
- tracemalloc.Filter(False, "<unknown>"),
- tracemalloc.Filter(False, tracemalloc.__file__)
- )
- stats_top_n = 10
- tracemalloc.start()
- snapshot_begin = tracemalloc.take_snapshot().filter_traces(snapshot_filter_traces)
- # ... run your application ...
- snapshot_end = tracemalloc.take_snapshot().filter_traces(snapshot_filter_traces)
- stats = snapshot_end.compare_to(snapshot_begin, 'lineno', cumulative=True)
- pretty_stats = create_pretty_stats(stats, limit=stats_top_n)
- print('\n'.join(pretty_stats))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement