我正在使用
Python编写的某种系统服务(实际上只是一个日志解析器).这个程序应该连续工作很长时间(希望我的意思是几天和几周,没有失败和重新启动的需要).这就是为什么我关心内存消耗.
我将来自不同站点的进程内存使用的不同信息汇总成一个简单的功能:
#!/usr/bin/env python
from pprint import pprint
from guppy import hpy
from datetime import datetime
import sys
import os
import resource
import re
def debug_memory_leak():
#Getting virtual memory size
pid = os.getpid()
with open(os.path.join("/proc", str(pid), "status")) as f:
lines = f.readlines()
_vmsize = [l for l in lines if l.startswith("VmSize")][0]
vmsize = int(_vmsize.split()[1])
#Getting physical memory size
pmsize = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
#Analyzing the dynamical memory segment - total number of objects in memory and heap size
h = hpy().heap()
if __debug__:
print str(h)
m = re.match(
"Partition of a set of ([0-9]+) objects. Total size = ([0-9]+) bytes(.*)", str(h))
objects = m.group(1)
heap = int(m.group(2))/1024 #to Kb
current_time = datetime.now().strftime("%H:%M:%S")
data = (current_time, objects, heap, pmsize, vmsize)
print("\t".join([str(d) for d in data]))
这个功能已经被用来研究长时间播放过程的内存消耗的动态,我仍然不能解释它的行为.在二十分钟内物理和虚拟内存增加了11%和1%时,您可以看到堆大小和对象总数没有改变.
UPD:这个过程已经工作了将近15个小时.堆还是一样的,但物理内存增加了六倍,虚拟内存增加了50%.曲线似乎是线性的,除了奇怪的离群值在凌晨3点:
Time Obj Heap PhM VM
19:04:19 31424 3928 5460 143732
19:04:29 30582 3704 10276 158240
19:04:39 30582 3704 10372 157772
19:04:50 30582 3709 10372 157772
19:05:00 30582 3704 10372 157772
(…)
19:25:00 30583 3704 11524 159900
09:53:23 30581 3704 62380 210756
我不知道我的进程的地址空间发生了什么.堆的不变大小表明所有动态对象被正确地释放.但是,毫无疑问,从长远来看,日益增长的内存消耗将会影响到这个关键生命过程的可持续性.
有人可以澄清这个问题吗?谢谢.
(我使用RHEL 6.4,内核2.6.32-358与Python 2.6.6)