是否有一种方法可以让Python程序确定它当前使用了多少内存?我看到过关于单个对象的内存使用情况的讨论,但我需要的是进程的总内存使用情况,这样我就可以确定何时需要开始丢弃缓存的数据。


当前回答

对于Unix系统,如果您传递-v,命令time (/usr/bin/time)将提供该信息。参见下面的最大驻留集大小,这是程序执行期间使用的最大(峰值)真实(而不是虚拟)内存:

$ /usr/bin/time -v ls /

    Command being timed: "ls /"
    User time (seconds): 0.00
    System time (seconds): 0.01
    Percent of CPU this job got: 250%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00
    Average shared text size (kbytes): 0
    Average unshared data size (kbytes): 0
    Average stack size (kbytes): 0
    Average total size (kbytes): 0
    Maximum resident set size (kbytes): 0
    Average resident set size (kbytes): 0
    Major (requiring I/O) page faults: 0
    Minor (reclaiming a frame) page faults: 315
    Voluntary context switches: 2
    Involuntary context switches: 0
    Swaps: 0
    File system inputs: 0
    File system outputs: 0
    Socket messages sent: 0
    Socket messages received: 0
    Signals delivered: 0
    Page size (bytes): 4096
    Exit status: 0

其他回答

在Windows上,你可以使用WMI(主页,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)

在Linux上(来自python烹饪书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

对于Unix系统,如果您传递-v,命令time (/usr/bin/time)将提供该信息。参见下面的最大驻留集大小,这是程序执行期间使用的最大(峰值)真实(而不是虚拟)内存:

$ /usr/bin/time -v ls /

    Command being timed: "ls /"
    User time (seconds): 0.00
    System time (seconds): 0.01
    Percent of CPU this job got: 250%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00
    Average shared text size (kbytes): 0
    Average unshared data size (kbytes): 0
    Average stack size (kbytes): 0
    Average total size (kbytes): 0
    Maximum resident set size (kbytes): 0
    Average resident set size (kbytes): 0
    Major (requiring I/O) page faults: 0
    Minor (reclaiming a frame) page faults: 315
    Voluntary context switches: 2
    Involuntary context switches: 0
    Swaps: 0
    File system inputs: 0
    File system outputs: 0
    Socket messages sent: 0
    Socket messages received: 0
    Signals delivered: 0
    Page size (bytes): 4096
    Exit status: 0

Linux上当前进程的当前内存使用情况,适用于Python 2、Python 3和pypy,没有任何导入:

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())

它读取当前进程的状态文件,取VmRSS:之后的所有内容,然后取第一个换行符之前的所有内容(隔离VmRSS的值),最后切掉最后3个字节,即一个空格和单位(kB)。 为了返回,它删除任何空白并将其作为数字返回。

在Linux 4.4和4.9上进行了测试,但即使是早期的Linux版本也应该工作:在man proc中查找/proc/$PID/status文件中的信息,它提到了一些字段的最低版本(如Linux 2.6.10的“VmPTE”),但“VmRSS”字段(我在这里使用)没有这样的提及。因此,我认为它已经在那里的早期版本。

下面是我的函数装饰器,它可以跟踪这个进程在函数调用之前消耗了多少内存,在函数调用之后使用了多少内存,以及函数执行了多长时间。

import time
import os
import psutil


def elapsed_since(start):
    return time.strftime("%H:%M:%S", time.gmtime(time.time() - start))


def get_process_memory():
    process = psutil.Process(os.getpid())
    return process.memory_info().rss


def track(func):
    def wrapper(*args, **kwargs):
        mem_before = get_process_memory()
        start = time.time()
        result = func(*args, **kwargs)
        elapsed_time = elapsed_since(start)
        mem_after = get_process_memory()
        print("{}: memory before: {:,}, after: {:,}, consumed: {:,}; exec time: {}".format(
            func.__name__,
            mem_before, mem_after, mem_after - mem_before,
            elapsed_time))
        return result
    return wrapper

当你用它来装饰某个函数时

from utils import track

@track
def list_create(n):
    print("inside list create")
    return [1] * n

你将会看到这样的输出:

inside list create
list_create: memory before: 45,928,448, after: 46,211,072, consumed: 282,624; exec time: 00:00:00

对于基于Unix的系统(Linux、Mac OS X、Solaris),可以使用标准库模块资源中的getrusage()函数。结果对象具有ru_maxrss属性,该属性给出了调用进程的内存使用峰值:

>>> resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
2656  # peak memory usage (kilobytes on Linux, bytes on OS X)

Python文档不记录单位。请参考您的特定系统的man getusage。2页检查该单位的值。在Ubuntu 18.04中,单位是千字节。在Mac OS X上,它是字节。

getrusage()函数也可以被赋予资源。获取子进程和(在某些系统上)资源的使用情况。RUSAGE_BOTH用于总(自我和子)进程使用情况。

如果你只关心Linux,你也可以阅读/proc/self/status或/proc/self/statm文件,就像这个问题和这个问题的其他答案中描述的那样。