我想在Linux系统中(特别是Ubuntu 15.04),测量进程的内存使用情况,但我不确定如何正确完成。我希望这些测量结果与
到目前为止,我已经编写了此Python脚本,但它与
free
命令相关,以便发现的总内存使用量对应于free
报告的值(缓存除外)。到目前为止,我已经编写了此Python脚本,但它与
free
不一致,因为它报告较低的总内存使用量:#!/usr/bin/env python
from collections import OrderedDict
import os.path
import re
def parse_mem_file(filename):
data = OrderedDict()
with open(filename, 'rb') as f:
for line in f:
splittage = line.split(':')
data[splittage[0]] = splittage[1].strip()
return data
def get_process_mem_usage():
re_pid = re.compile(r'^\d+$')
re_mem = re.compile(r'^(\d+) .+$')
pid2usage = {}
for pid in [d for d in os.listdir('/proc') if re_pid.match(d)]:
fpath = os.path.join('/proc', pid, 'status')
try:
data = parse_mem_file(fpath)
except IOError:
continue
try:
pid2usage[pid] = int(re_mem.match(data['VmHWM']).group(1)) / 1024.
except KeyError:
continue
return OrderedDict(
sorted(pid2usage.iteritems(), key=lambda x: x[1], reverse=True))
pid2usage = get_process_mem_usage()
total_usage = sum(pid2usage.values())
print('Total memory usage: {:.2f}'.format(total_usage))
for pid, usage in pid2usage.iteritems():
print('{}: {:.2f} MB'.format(pid, usage))
如何调整此程序以报告与free
程序报告相符的内存使用情况?
为了理解背景,问题是我的服务器上的内存使用量随着时间的推移而增加,直到大量交换内存被使用并因此导致速度变慢。我想知道这个问题的原因。
top
发现它正在使用大约780 MB的交换空间。 - aknuds1