You could also use the getrusage()
function from the standard library module resource
. The resulting object has the attribute ru_maxrss
, which gives total peak memory usage for the calling process:
>>> import resource
>>> resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
2656
The Python docs aren't clear on what the units are exactly, but the Mac OS X man page for getrusage(2)
describes the units as kilobytes.
The Linux man page isn't clear, but it seems to be equivalent to the /proc/self/status
information (i.e. kilobytes) described in the accepted answer. For the same process as above, running on Linux, the function listed in the accepted answer gives:
>>> memory_usage()
{'peak': 6392, 'rss': 2656}
This may not be quite as easy to use as the /proc/self/status
solution, but it is standard library, so (provided the units are standard) it should be cross-platform, and usable on systems which lack /proc/
(eg Mac OS X and other Unixes, maybe Windows).
Also, 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.
This will cover the memory_get_usage()
case, but doesn't include peak usage. I'm unsure if any other functions from the resource
module can give peak usage.