Python psutil memory_info 上限为 4.0G

Python psutil memory_info caps at 4.0G

我正在尝试根据 python psutil 模块的内存消耗列出 运行 中所有 运行 进程并对其进行排序。但是,当我查询进程 memory_info 属性时,各种指标的 none 将超过 4 GB。为什么会受到限制?我该如何解决?

我确实尝试使用 proc.memory_full_info(),理论上可以解决 uss 内存指标的这个问题,但是我不知道如何在不导致 AccessDenied 错误的情况下做到这一点。

示例脚本:

import psutil
from psutil._common import bytes2human

procs = [p.info for p in psutil.process_iter(attrs=['memory_info', 'memory_percent', 'name'])]

for proc in sorted(procs, key=lambda p: p['memory_percent'], reverse=True):
    print("{} - {}".format(proc['name'], bytes2human(getattr(proc['memory_info'], 'rss'))))

我愿意接受任何其他分析内存使用情况的方法,psutil 似乎是我发现的最好的工具。

您正在使用32位Python。默认情况下,32bit 进程有 4GiB 内存限制。在软件级别,该限制来自底层 C 类型限制(并且 psutil 的核心是用 C).
例如,几乎所有 [MS.Docs]: PROCESS_MEMORY_COUNTERS structure 成员都有 SIZE_T 类型。

示例:

  • 32位:

    >>> import sys, ctypes
    >>> from ctypes import wintypes
    >>> sys.version
    '3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)]'
    >>>
    >>> ctypes.sizeof(wintypes.DWORD), ctypes.sizeof(ctypes.c_size_t), ctypes.sizeof(wintypes.HANDLE)
    (4, 4, 4)
    
  • 64位:

    >>> import sys, ctypes
    >>> from ctypes import wintypes
    >>> sys.version
    '3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)]'
    >>>
    >>> ctypes.sizeof(wintypes.DWORD), ctypes.sizeof(ctypes.c_size_t), ctypes.sizeof(wintypes.HANDLE)
    (4, 8, 8)
    

有关如何区分不同 CPU 架构的更多详细信息 Python,请查看:[SO]: How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? (@CristiFati's answer)