Skip to content

Instantly share code, notes, and snippets.

@KavenTheriault
Created December 23, 2019 15:23
Show Gist options
  • Save KavenTheriault/b8c60401eaddb99a6857fbf5f2161b88 to your computer and use it in GitHub Desktop.
Save KavenTheriault/b8c60401eaddb99a6857fbf5f2161b88 to your computer and use it in GitHub Desktop.
Python memory profiling

Use de "track_memory" decorator on your functions.

import os
import psutil
def get_process_memory():
process = psutil.Process(os.getpid())
return process.memory_info().rss
def track_memory(func):
def wrapper(*args, **kwargs):
mem_before = get_process_memory()
result = func(*args, **kwargs)
mem_after = get_process_memory()
print(
"{}: memory before: {:,}, after: {:,}, consumed: {:,}".format(
func.__name__, mem_before, mem_after, mem_after - mem_before
)
)
return result
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment