mercurial/utils/memorytop.py
changeset 45797 5b6c0af021da
equal deleted inserted replaced
45796:e9555305c5c6 45797:5b6c0af021da
       
     1 # memorytop requires Python 3.4
       
     2 #
       
     3 # Usage: set PYTHONTRACEMALLOC=n in the environment of the hg invocation,
       
     4 # where n>= is the number of frames to show in the backtrace. Put calls to
       
     5 # memorytop in strategic places to show the current memory use by allocation
       
     6 # site.
       
     7 
       
     8 import gc
       
     9 import tracemalloc
       
    10 
       
    11 
       
    12 def memorytop(limit=10):
       
    13     gc.collect()
       
    14     snapshot = tracemalloc.take_snapshot()
       
    15 
       
    16     snapshot = snapshot.filter_traces(
       
    17         (
       
    18             tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
       
    19             tracemalloc.Filter(False, "<frozen importlib._bootstrap_external>"),
       
    20             tracemalloc.Filter(False, "<unknown>"),
       
    21         )
       
    22     )
       
    23     stats = snapshot.statistics('traceback')
       
    24 
       
    25     total = sum(stat.size for stat in stats)
       
    26     print("\nTotal allocated size: %.1f KiB\n" % (total / 1024))
       
    27     print("Lines with the biggest net allocations")
       
    28     for index, stat in enumerate(stats[:limit], 1):
       
    29         print(
       
    30             "#%d: %d objects using %.1f KiB"
       
    31             % (index, stat.count, stat.size / 1024)
       
    32         )
       
    33         for line in stat.traceback.format(most_recent_first=True):
       
    34             print('    ', line)
       
    35 
       
    36     other = stats[limit:]
       
    37     if other:
       
    38         size = sum(stat.size for stat in other)
       
    39         count = sum(stat.count for stat in other)
       
    40         print(
       
    41             "%s other: %d objects using %.1f KiB"
       
    42             % (len(other), count, size / 1024)
       
    43         )
       
    44     print()