使用python定时采样linux内存使用情况

时间:2023-01-03 22:30:55
# -*- coding: utf-8 -*-

import threading, time

class GetMemInfo(threading.Thread):
def __init__(self, interval_time):
threading.Thread.__init__(self)
self.alive = True
self.mem_list = []
self._interval_time = interval_time

def memory_stat(self):
'''读取meminfo,计算用户占用的内存'''
_mem = {}
with open("/proc/meminfo") as f:
lines = f.readlines()

for line in lines:
if line.strip() == "":
continue
name = line.split(':')[0].strip()
var = line.split(':')[1].split()[0].strip()
_mem[name] = int(var) * 1024.0
_mem['MemUsed'] = _mem['MemTotal'] - _mem['MemFree'] - _mem['Buffers'] - _mem['Cached']
return _mem

def run(self):
while self.alive:
time.sleep(self._interval_time)
mem = self.memory_stat()
self.mem_list.append(mem['MemUsed'])

def stop_task(self):
self.alive = False

def get_mem(self):
return self.mem_list


if __name__ == "__main__":
# 每2秒采样一次
mem = GetMemInfo(2)
mem.start()
time.sleep(10)
mem.stop_task()
print mem.get_mem()