[英]Determine free RAM in Python
我希望我的python腳本能夠使用所有可用的RAM而不是更多(出於效率原因)。 我可以通過只讀取有限數量的數據來控制它,但我需要知道在運行時有多少RAM是免費的才能做到這一點。 它將在各種Linux系統上運行。 是否可以在運行時確定空閑RAM?
在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
您可以在腳本啟動時運行此命令。 RAM通常在繁忙的系統上經常使用和釋放,因此在決定使用多少RAM之前應考慮到這一點。 此外,大多數Linux系統的swappiness值為60.使用內存時,最常使用的頁面將被換出。 您可能會發現自己使用的是SWAP而不是RAM。
希望這可以幫助。
你可以讀出/proc/meminfo
。 請注意,“空閑內存”通常很低,因為操作系統大量使用免費的未使用內存進行緩存。
此外,最好不要試圖超越操作系統的內存管理。 這通常只是以淚水(或較慢的程序)結束。 最好只需要你需要的RAM。 如果你想在具有以前未知內存量的機器上盡可能多地使用,我可能會檢查安裝了多少RAM( /proc/meminfo
MemTotal
),為操作系統留出一定的數量並作為安全措施保證金(比如1 GB)並使用其余部分。
由於原始海報寫的代碼應該在各種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
碼:
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
另一個選項是內置的Python包psutil
:
stats = psutil.virtual_memory() # returns a named tuple
available = getattr(stats, 'available')
print(available)
根據文檔 , available
字段“是通過根據平台對不同的內存值求和來計算的,它應該用於監視跨平台方式的實際內存使用情況。”
請注意,返回值將以字節為單位
我想你可以使用免費的 ( http://www.cyberciti.biz/faq/linux-check-memory-usage/ ),PS或者也許MemoryMonitor類從張貼在我的答案最底層的SO-線程做這個。 只是減少一些松弛,並留下一些少量的ram用於其他進程,如果他們迫切需要它,以避免代表他們的磁盤寫入。
如果你使用它,你將需要解析free或ps的輸出,但這不應該很難。 請記住,您需要實時分析可用的ram,因此您可以調整其他進程是否因某種原因而導致內存耗盡。
另見這個帖子: 如何在Python中獲取當前的CPU和RAM使用率?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.