Skip to content

Instantly share code, notes, and snippets.

@zbentley
Created December 24, 2023 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zbentley/e0112b5f1d9c0d1a78e6fae557252089 to your computer and use it in GitHub Desktop.
Save zbentley/e0112b5f1d9c0d1a78e6fae557252089 to your computer and use it in GitHub Desktop.
Python resource-based coarse memory growth observer
import contextlib
import resource
import typing
memory_profiler_data = dict()
@contextlib.contextmanager
def record_memory(name: str) -> typing.ContextManager:
initial_rusage = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
assert name not in memory_profiler_data, f"{name}'s memory usage has already been recorded, can't record again"
try:
yield
finally:
memory_profiler_data[name] = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss - initial_rusage
def main():
with record_memory('operation1'):
do_stuff_for_operation1()
with record_memory('operation2'):
do_stuff_for_operation2()
print(memory_profiler_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment