确定Python中的空闲RAM

mar*_*all 14 python memory-management

我希望我的python脚本能够使用所有可用的RAM而不是更多(出于效率原因).我可以通过只读取有限数量的数据来控制它,但我需要知道在运行时有多少RAM是免费的才能做到这一点.它将在各种Linux系统上运行.是否可以在运行时确定空闲RAM?

Gab*_*ira 20

在Linux系统上我不时使用它:

def memory():
    """
    Get node total memory and memory usage
    """
    with open('/proc/meminfo', 'r') as mem:
        ret = {}
        tmp = 0
        for i in mem:
            sline = i.split()
            if str(sline[0]) == 'MemTotal:':
                ret['total'] = int(sline[1])
            elif str(sline[0]) in ('MemFree:', 'Buffers:', 'Cached:'):
                tmp += int(sline[1])
        ret['free'] = tmp
        ret['used'] = int(ret['total']) - int(ret['free'])
    return ret
Run Code Online (Sandbox Code Playgroud)

您可以在脚本启动时运行此命令.RAM通常在繁忙的系统上经常使用和释放,因此在决定使用多少RAM之前应考虑到这一点.此外,大多数Linux系统的swappiness值为60.使用内存时,最常使用的页面将被换出.您可能会发现自己使用的是SWAP而不是RAM.

希望这可以帮助.


Car*_*ten 7

你可以读出来/proc/meminfo.请注意,"空闲内存"通常很低,因为操作系统大量使用免费的未使用内存进行缓存.

此外,最好不要试图超越操作系统的内存管理.这通常只是以泪水(或较慢的程序)结束.最好只需要你需要的RAM.如果你想在具有以前未知内存量的机器上尽可能多地使用,我可能会检查安装了多少RAM(MemTotal/proc/meminfo),为操作系统留出一定数量的安全余量(比如1 GB)并使用其余的.

  • @nic`/ proc/meminfo`及其当前值集[至少从Linux 2.6开始提供](http://linux.die.net/man/5/proc).这应该足够长. (2认同)

Oz1*_*123 5

由于原始发布者写的代码应该在各种Linux系统上运行,因此我在这里发布了一个面向对象的 Linux 内存查询解决方案。psutil是一个很棒的库,但如果由于某种原因无法安装它,您可以简单地使用以下解决方案:

用法示例:

>>> f = FreeMemLinux()
>>> print f.total, f.used,  f.user_free
8029212 3765960 4464816
>>>
>>> f_mb = FreeMemLinux(unit='MB')
>>> print f_mb.total, f_mb.used,  f_mb.user_free
7841.02734375 3677.6953125 4360.171875
>>>
>>> f_percent = FreeMemLinux(unit='%')
>>> print f_percent.total, f_percent.used, f_percent.user_free
100.0 46.9032328453 55.60715049
Run Code Online (Sandbox Code Playgroud)

代码:

class FreeMemLinux(object):
    """
    Non-cross platform way to get free memory on Linux. Note that this code
    uses the `with ... as`, which is conditionally Python 2.5 compatible!
    If for some reason you still have Python 2.5 on your system add in the
head of your code, before all imports:
    from __future__ import with_statement
    """

    def __init__(self, unit='kB'):

        with open('/proc/meminfo', 'r') as mem:
            lines = mem.readlines()

        self._tot = int(lines[0].split()[1])
        self._free = int(lines[1].split()[1])
        self._buff = int(lines[2].split()[1])
        self._cached = int(lines[3].split()[1])
        self._shared = int(lines[20].split()[1])
        self._swapt = int(lines[14].split()[1])
        self._swapf = int(lines[15].split()[1])
        self._swapu = self._swapt - self._swapf

        self.unit = unit
        self._convert = self._factor()

    def _factor(self):
        """determine the convertion factor"""
        if self.unit == 'kB':
            return 1
        if self.unit == 'k':
            return 1024.0
        if self.unit == 'MB':
            return 1/1024.0
        if self.unit == 'GB':
            return 1/1024.0/1024.0
        if self.unit == '%':
            return 1.0/self._tot
        else:
            raise Exception("Unit not understood")

    @property
    def total(self):
        return self._convert * self._tot

    @property
    def used(self):
        return self._convert * (self._tot - self._free)

    @property
    def used_real(self):
        """memory used which is not cache or buffers"""
        return self._convert * (self._tot - self._free -
                                self._buff - self._cached)

    @property
    def shared(self):
        return self._convert * (self._tot - self._free)

    @property
    def buffers(self):
        return self._convert * (self._buff)

    @property
    def cached(self):
        return self._convert * self._cached

    @property
    def user_free(self):
        """This is the free memory available for the user"""
        return self._convert *(self._free + self._buff + self._cached)

    @property
    def swap(self):
        return self._convert * self._swapt

    @property
    def swap_free(self):
        return self._convert * self._swapf

    @property
    def swap_used(self):
        return self._convert * self._swapu
Run Code Online (Sandbox Code Playgroud)


Add*_*nke 5

另一种选择是内置的 Python 包psutil

stats = psutil.virtual_memory()  # returns a named tuple
available = getattr(stats, 'available')
print(available)
Run Code Online (Sandbox Code Playgroud)

根据文档,该available字段“是通过根据平台对不同的内存值求和来计算的,它应该用于以跨平台方式监控实际内存使用情况。”

注意返回值将以字节为单位

  • 它是一个内置的Python包吗? (2认同)
  • `psutil` 不是内置包;相反,您必须先“pip install psutil”。 (2认同)