今天介紹獲取本機記憶體狀況並將其儲存的Python程式.
系統記憶體的使用狀況對我們了解系統運作情況及判斷瓶頸,
有重要的參考價值,系統雖然提供許多細緻的指令,來了解
當前記憶體的使用狀況,若能長期的蒐集,對系統記憶體後續
的增加就有數據提供參考.或是使用者反應某某時段系統反應
較慢,我們即可利用蒐集的歷史數據,進行判斷.
以下為建立資料檔的Python程式.
#!/usr/bin/env python
# -------------------
# Create Memory RRD
# -------------------
import rrdtool
rrdtool.create(
'memory.rrd', '--step', '60',
'DS:mtotl:GAUGE:120:0:U',
'DS:mbuff:GAUGE:120:0:U',
'DS:mcach:GAUGE:120:0:U',
'DS:mfree:GAUGE:120:0:U',
'RRA:AVERAGE:0.5:1:2880',
'RRA:AVERAGE:0.5:30:672',
'RRA:AVERAGE:0.5:60:744',
'RRA:AVERAGE:0.5:720:732',
'RRA:MAX:0.5:1:2880',
'RRA:MAX:0.5:30:672',
'RRA:MAX:0.5:60:744',
'RRA:MAX:0.5:720:732',
'RRA:MIN:0.5:1:2880',
'RRA:MIN:0.5:30:672',
'RRA:MIN:0.5:60:744',
'RRA:MIN:0.5:720:732',
'RRA:LAST:0.5:1:2880',
'RRA:LAST:0.5:30:672',
'RRA:LAST:0.5:60:744',
'RRA:LAST:0.5:720:732')
執行後會建立資料檔,接著是蒐集資料的程式.
#!/usr/bin/env python
# -------------------
# Update Memory RRD
# -------------------
import rrdtool
import time
def get_meminfo():
with open('/proc/meminfo', 'r') as memtxt:
mem_list = ('total', 'free', 'buffer', 'cached')
mems = memtxt.readlines()
for mem in mems:
item, vals = mem.split(':')
if item == 'MemTotal':
memtot = int(vals.split()[0])
if item == 'MemFree':
memfree = int(vals.split()[0])
if item == 'Buffers':
membuff = int(vals.split()[0])
if item == 'Cached':
memcach = int(vals.split()[0])
#
memdict = dict(zip(mem_list, (memtot, memfree, membuff, memcach)))
return memdict
#
def update_mem_rrd(rrdfile):
""" update memory rrd file"""
memdict = get_meminfo()
total = memdict['total']
free = memdict['free']
mbuffer = memdict['buffer']
cached = memdict['cached']
rrdtool.update(rrdfile, 'N:' + `total` + ':' + `mbuffer` \
+ ':' + `cached` + ':' + `free`)
#
if __name__ == '__main__':
while 1:
update_mem_rrd('memory.rrd')
time.sleep(60)
放到背景執行,會每分鐘更新數據.