简体   繁体   English

确定Python中的空闲RAM

[英]Determine free RAM in Python

I would like my python script to use all the free RAM available but no more (for efficiency reasons). 我希望我的python脚本能够使用所有可用的RAM而不是更多(出于效率原因)。 I can control this by reading in only a limited amount of data but I need to know how much RAM is free at run-time to get this right. 我可以通过只读取有限数量的数据来控制它,但我需要知道在运行时有多少RAM是免费的才能做到这一点。 It will be run on a variety of Linux systems. 它将在各种Linux系统上运行。 Is it possible to determine the free RAM at run-time? 是否可以在运行时确定空闲RAM?

On Linux systems I use this from time to time: 在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

You can run this when your script starts up. 您可以在脚本启动时运行此命令。 RAM is usually used and freed pretty frequently on a busy system, so you should take that into account before deciding how much RAM to use. RAM通常在繁忙的系统上经常使用和释放,因此在决定使用多少RAM之前应考虑到这一点。 Also, most linux systems have a swappiness value of 60. When using up memory, pages that are least frequently used will be swapped out. 此外,大多数Linux系统的swappiness值为60.使用内存时,最常使用的页面将被换出。 You may find yourself using SWAP instead of RAM. 您可能会发现自己使用的是SWAP而不是RAM。

Hope this helps. 希望这可以帮助。

You could just read out /proc/meminfo . 你可以读出/proc/meminfo Be aware that the "free memory" is usually quite low, as the OS heavily uses free, unused memory for caching. 请注意,“空闲内存”通常很低,因为操作系统大量使用免费的未使用内存进行缓存。

Also, it's best if you don't try to outsmart your OS's memory management. 此外,最好不要试图超越操作系统的内存管理。 That usually just ends in tears (or slower programs). 这通常只是以泪水(或较慢的程序)结束。 Better just take the RAM you need. 最好只需要你需要的RAM。 If you want to use as much as you can on a machine with a previously unknown amount of memory, I'd probably check how much RAM is installed ( MemTotal in /proc/meminfo ), leave a certain amount for the OS and as safety margin (say 1 GB) and use the rest. 如果你想在具有以前未知内存量的机器上尽可能多地使用,我可能会检查安装了多少RAM( /proc/meminfo MemTotal ),为操作系统留出一定的数量并作为安全措施保证金(比如1 GB)并使用其余部分。

Since the original poster wrote the code should run on a variety of Linux system, I am posting here an Object oriented solution for Linux Memory query. 由于原始海报写的代码应该在各种Linux系统上运行,我在这里发布一个面向对象的Linux内存查询解决方案。 psutil is a great library, but if you can't install it for some reason, you can simply use the following solution: psutil是一个很棒的库,但如果由于某种原因无法安装它,您只需使用以下解决方案:

Example usage: 用法示例:

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

Code: 码:

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

Another option is the built-in Python package psutil : 另一个选项是内置的Python包psutil

stats = psutil.virtual_memory()  # returns a named tuple
available = getattr(stats, 'available')
print(available)

According to the documentation , the available field "is calculated by summing different memory values depending on the platform and it is supposed to be used to monitor actual memory usage in a cross platform fashion." 根据文档available字段“是通过根据平台对不同的内存值求和来计算的,它应该用于监视跨平台方式的实际内存使用情况。”

Note the return value will be in bytes 请注意,返回值将以字节为单位

I suppose you could use free ( http://www.cyberciti.biz/faq/linux-check-memory-usage/ ), ps or maybe the MemoryMonitor class from the SO-thread posted at the very bottom of my answer to do this. 我想你可以使用免费的http://www.cyberciti.biz/faq/linux-check-memory-usage/ ),PS或者也许MemoryMonitor类从张贴在我的答案最底层的SO-线程做这个。 Just cut some slack and leave some small amount of ram unused for other processes if they should need it urgently yo avoid disk writes on their behalf. 只是减少一些松弛,并留下一些少量的ram用于其他进程,如果他们迫切需要它,以避免代表他们的磁盘写入。

You will need to parse the output from free or ps if you use that, but that shouldn't be hard. 如果你使用它,你将需要解析free或ps的输出,但这不应该很难。 Remember that you need to analyze available ram real time, so you can adjust if another process gets memory hungry for some reason. 请记住,您需要实时分析可用的ram,因此您可以调整其他进程是否因某种原因而导致内存耗尽。

also see this thread: How to get current CPU and RAM usage in Python? 另见这个帖子: 如何在Python中获取当前的CPU和RAM使用率?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM