Skip to content

Instantly share code, notes, and snippets.

@loretoparisi
Created May 6, 2021 12:49
Show Gist options
  • Save loretoparisi/533b4b0951101e7e68788e2ed61f124b to your computer and use it in GitHub Desktop.
Save loretoparisi/533b4b0951101e7e68788e2ed61f124b to your computer and use it in GitHub Desktop.
Python Memory Alloc Trace
def trace_mem(nframe=6,top=8):
'''
naive memory trace
'''
import tracemalloc
is_tracing = tracemalloc.is_tracing()
if not is_tracing:
# start tracing
tracemalloc.start(nframe)
return {}
else:
# read traced memory alloc
current_mem, peak_mem = tracemalloc.get_traced_memory()
overhead = tracemalloc.get_tracemalloc_memory()
stats = tracemalloc.take_snapshot().statistics('traceback')[:top]
# memory summary
summary = {}
summary['memory'] = int(current_mem // 1024)
summary['peak'] = int(peak_mem // 1024)
summary['overhead'] = int(overhead // 1024)
summary['description'] = "traced memory: %d KiB peak: %d KiB overhead: %d KiB" % (
int(current_mem // 1024), int(peak_mem // 1024), int(overhead // 1024)
)
# traceback
out_lines = []
for trace in stats:
stacktrace = {}
stacktrace['memory'] = int(trace.size // 1024)
stacktrace['blocks'] = int(trace.count)
stacktrace['stack'] = trace.traceback.format()
out_lines.append(stacktrace)
data = {}
data['summary'] = summary
data['traceback'] = out_lines
# stop tracing
tracemalloc.stop()
return data
@loretoparisi
Copy link
Author

Use like this

import json
# start memory tracing
trace_mem(nframe=6, top=8)
## do your heavy and memory-bound job
# dump memory and stop tracing
print("\n--------mem--------\n", json.dumps(trace_mem(nframe=6, top=8), indent=4), "\n--------mem--------")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment