Total memory used by Python process?

前端 未结 12 829
眼角桃花
眼角桃花 2020-11-22 04:28

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

12条回答
  •  孤城傲影
    2020-11-22 04:53

    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.

提交回复
热议问题