For Unix based systems (Linux, Mac OS X, Solaris), you can use the getrusage()
function from the standard library module resource
. The resulting object has the attribute ru_maxrss
, which gives the peak memory usage for the calling process:
>>> resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
2656 # peak memory usage (kilobytes on Linux, bytes on OS X)
The Python docs don't make note of the units. Refer to your specific system's man getrusage.2
page to check the unit for the value. On Ubuntu 18.04, the unit is noted as kilobytes. On Mac OS X, it's bytes.
The getrusage()
function can also be given resource.RUSAGE_CHILDREN
to get the usage for child processes, and (on some systems) resource.RUSAGE_BOTH
for total (self and child) process usage.
If you care only about Linux, you can alternatively read the /proc/self/status
or /proc/self/statm
file as described in other answers for this question and this one too.