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.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Current memory usage of the current process on Linux, for Python 2, Python 3, and pypy, without any imports:
Tested on Linux 4.4 and 4.9, but even an early Linux version should work.
Looking in
man proc
and searching for the info on the/proc/$PID/status
file, it mentions minimum versions for some fields (like Linux 2.6.10 for "VmPTE"), but the "VmRSS" field (which I use here) has no such mention. Therefore I assume it has been in there since an early version.For Unixes (Linux, Mac OS X, Solaris) you could also use the
getrusage()
function from the standard library moduleresource
. The resulting object has the attributeru_maxrss
, which gives peak memory usage for the calling process: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 bytes. The Linux man page isn't clear, but it seems to be equivalent to the information from/proc/self/status
, which is in kilobytes.The
getrusage()
function can also be givenresource.RUSAGE_CHILDREN
to get the usage for child processes, and (on some systems)resource.RUSAGE_BOTH
for total (self and child) process usage.resource
is a standard library module.If you only care about Linux, you can just check the
/proc/self/status
file as described in a similar question.On Windows, you can use WMI (home page, cheeseshop):
On Linux (from python cookbook http://code.activestate.com/recipes/286222/:
Even easier to use than
/proc/self/status
:/proc/self/statm
. It's just a space delimited list of several statistics. I haven't been able to tell if both files are always present.Here's a simple example:
That produces a list that looks something like this:
You can see that it jumps by about 300,000 bytes after roughly 3 allocations of 100,000 bytes.
On unix, you can use the
ps
tool to monitor it:where 1347 is some process id. Also, the result is in MB.