Total memory used by Python process?

rwallace picture rwallace · Jun 2, 2009 · Viewed 255.6k times · Source

Is there a way for a Python program to determine how much memory it's currently using? I've seen discussions about memory usage for a single object, but what I need is total memory usage for the process, so that I can determine when it's necessary to start discarding cached data.

Answer

Basj picture Basj · Feb 7, 2014

Here is a useful solution that works for various operating systems, including Linux, Windows, etc.:

import os
import psutil
process = psutil.Process(os.getpid())
print(process.memory_info().rss)  # in bytes 

With Python 2.7 and psutil 5.6.3, the last line should be

print(process.memory_info()[0])

instead (there was a change in the API later).

Note: do pip install psutil if it is not installed yet.