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 tot
Current memory usage of the current process on Linux, for Python 2, Python 3, and pypy, without any imports:
def getCurrentMemoryUsage():
''' Memory usage in kB '''
with open('/proc/self/status') as f:
memusage = f.read().split('VmRSS:')[1].split('\n')[0][:-3]
return int(memusage.strip())
It reads the status file of the current process, takes everything after VmRSS:
, then takes everything before the first newline (isolating the value of VmRSS), and finally cuts off the last 3 bytes which are a space and the unit (kB).
To return, it strips any whitespace and returns it as a number.
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.