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.
+2
A:
Heapy (and friends) may be what you're looking for.
Also, caches typically have a fixed upper limit on their size to solve the sort of problem you're talking about. For instance, check out this LRU cache decorator.
Hank Gay
2009-06-02 09:55:47
+1
A:
On unix, you can use the ps
tool to monitor it:
$ ps u -p 1347 | awk '{sum=sum+$6}; END {print sum/1024}'
where 1347 is some process id. Also, the result is in MB.
bayer
2009-06-02 09:59:10
+9
A:
On Windows, you can use WMI (home page, cheeseshop):
def memory():
import os
from wmi import WMI
w = WMI('.')
result = w.query("SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % os.getpid())
return int(result[0]['WorkingSet'])
On Linux (from python cookbook http://code.activestate.com/recipes/286222/:
import os
_proc_status = '/proc/%d/status' % os.getpid()
_scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
'KB': 1024.0, 'MB': 1024.0*1024.0}
def _VmB(VmKey):
'''Private.
'''
global _proc_status, _scale
# get pseudo file /proc/<pid>/status
try:
t = open(_proc_status)
v = t.read()
t.close()
except:
return 0.0 # non-Linux?
# get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
i = v.index(VmKey)
v = v[i:].split(None, 3) # whitespace
if len(v) < 3:
return 0.0 # invalid format?
# convert Vm value to bytes
return float(v[1]) * _scale[v[2]]
def memory(since=0.0):
'''Return memory usage in bytes.
'''
return _VmB('VmSize:') - since
def resident(since=0.0):
'''Return resident memory usage in bytes.
'''
return _VmB('VmRSS:') - since
def stacksize(since=0.0):
'''Return stack size in bytes.
'''
return _VmB('VmStk:') - since
codeape
2009-06-02 10:13:40
The Windows code doesn't work for me. This change does: `return int(result[0].WorkingSet)`
John Fouhy
2010-08-31 00:46:09