1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| import tracemalloc
class MemoryTrace:
__slots__ = ('frame', 'mem_top', 'key_type', 'mapping_key_type')
def __init__(self, frame=1, mem_top=10, key_type="lineno"): self.frame = frame self.mem_top = mem_top self.key_type = key_type self.mapping_key_type = { "lineno": self.lineno, "traceback": self.traceback, "deference": self.deference, }
def __call__(self, func): def wrapper(*args, **kwargs): result = (self.mapping_key_type .get(self.key_type) (func, *args, **kwargs))
self.end()
return result
return wrapper
def lineno(self, func, *args, **kwargs): """ display the files that most top memory was allocated """ print("========lineno=======") tracemalloc.start() result = func(*args, **kwargs) snapshot = tracemalloc.take_snapshot() top_stats = snapshot.statistics("lineno")
for top in top_stats[0:self.mem_top]: print("mem-trace ", top)
return result
def traceback(self, func, *args, **kwargs): """ display the traceback of the biggest memory block """ print("========traceback=======") tracemalloc.start(self.frame) result = func(*args, **kwargs) snapshot = tracemalloc.take_snapshot() top_stats = snapshot.statistics("traceback") top_one = top_stats[0]
print("blocks count: %s" % top_one.count) print("size: %.1f KiB" % (top_one.size / 1024)) for top in top_one.traceback.format(): print("mem-trace ", top)
return result
def deference(self, func, *args, **kwargs): """ compute the deference between two snapshot """ tracemalloc.start(self.frame) snapshot_start = tracemalloc.take_snapshot() result = func(*args, **kwargs) snapshot_end = tracemalloc.take_snapshot() top_stats = snapshot_end.compare_to(snapshot_start, "lineno")
for top in top_stats[:self.mem_top]: print("mem-trace ", top)
return result
def end(self): trace_malloc_module_usage = tracemalloc.get_tracemalloc_memory() print("trace alloc module use memory: %.1f KiB" % (trace_malloc_module_usage / 1024))
current_size, peak_size = tracemalloc.get_traced_memory() print("current size: %.1f KiB" % (current_size / 1024)) print("peak size: %.1f KiB" % (peak_size / 1024))
def write(self, snapshot, filename): pass
|