Skip to content

Instantly share code, notes, and snippets.

@harabchuk
Created January 20, 2025 09:23
Show Gist options
  • Save harabchuk/15bcf866b0a1d010a2b7bebbd790dc26 to your computer and use it in GitHub Desktop.
Save harabchuk/15bcf866b0a1d010a2b7bebbd790dc26 to your computer and use it in GitHub Desktop.
Trace peak memory usage in python
from contextlib import contextmanager
import tracemalloc
@contextmanager
def mtrace():
tracemalloc.start()
yield
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(f"Peak memory usage: {peak / 1024 ** 2:.2f} MiB")
# usage
with mtrace():
func()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment