Skip to content

Instantly share code, notes, and snippets.

@Tjorriemorrie
Created March 27, 2018 23:34
Show Gist options
  • Select an option

  • Save Tjorriemorrie/b28e4289d9dba9b184d8a872d827cf1c to your computer and use it in GitHub Desktop.

Select an option

Save Tjorriemorrie/b28e4289d9dba9b184d8a872d827cf1c to your computer and use it in GitHub Desktop.

Revisions

  1. Tjorriemorrie created this gist Mar 27, 2018.
    24 changes: 24 additions & 0 deletions memalloc.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    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]
    # replace "/path/to/module/file.py" with "module/file.py"
    filename = os.sep.join(frame.filename.split(os.sep)[-2:])
    print("#%s: %s:%s: %.1f KiB"
    % (index, 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))