Created
December 24, 2023 17:26
-
-
Save zbentley/e0112b5f1d9c0d1a78e6fae557252089 to your computer and use it in GitHub Desktop.
Python resource-based coarse memory growth observer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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