Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. import linecache
  2. import os
  3. import tracemalloc
  4.  
  5. def create_pretty_stats(stats, key_type='lineno', limit=10):
  6. stats_list = sorted([stat for stat in stats], key=lambda k: k.size, reverse=True)
  7.  
  8. stats_lines = []
  9.  
  10. for index, stat in enumerate(stats_list[:limit], 1):
  11. frame = stat.traceback[0]
  12. filename = os.sep.join(frame.filename.split(os.sep)[-2:])
  13. stats_lines.append("#%s: %s:%s: %.1f KiB"
  14. % (index, filename, frame.lineno, stat.size / 1024))
  15. line = linecache.getline(frame.filename, frame.lineno).strip()
  16. if line:
  17. stats_lines.append(' %s' % line)
  18.  
  19. other = stats[limit:]
  20. if other:
  21. size = sum(stat.size for stat in other)
  22. stats_lines.append("%s other: %.1f KiB" % (len(other), size / 1024))
  23. total = sum(stat.size for stat in stats_list)
  24. stats_lines.append("Total allocated size: %.1f KiB" % (total / 1024))
  25.  
  26. return stats_lines
  27.  
  28. # traces that should not be displayed
  29. snapshot_filter_traces = (
  30. tracemalloc.Filter(False, "<frozen importlib._bootstrap_external>"),
  31. tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
  32. tracemalloc.Filter(False, "<unknown>"),
  33. tracemalloc.Filter(False, tracemalloc.__file__)
  34. )
  35.  
  36. stats_top_n = 10
  37.  
  38. tracemalloc.start()
  39.  
  40. snapshot_begin = tracemalloc.take_snapshot().filter_traces(snapshot_filter_traces)
  41.  
  42. # ... run your application ...
  43.  
  44. snapshot_end = tracemalloc.take_snapshot().filter_traces(snapshot_filter_traces)
  45.  
  46. stats = snapshot_end.compare_to(snapshot_begin, 'lineno', cumulative=True)
  47.  
  48. pretty_stats = create_pretty_stats(stats, limit=stats_top_n)
  49.  
  50. print('\n'.join(pretty_stats))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement