【问题标题】:Detecting memory leak in Python在 Python 中检测内存泄漏
【发布时间】:2015-03-23 15:46:06
【问题描述】:

我有一个作为服务运行的 python 模块。有没有办法检测正在运行的进程的内存泄漏?

到目前为止,我在网上看到的大多数工具,例如 muppy,要么只是给出所有正在运行的进程的内存使用情况(我有几个 python 进程),要么要求我将 python 代码作为工具的一部分运行(由于我的代码作为服务运行,因此我无法执行此操作)。

知道如何至少捕获内存使用情况,甚至可以从那里检测内存泄漏吗?

【问题讨论】:

  • 如果您无法修改源代码,您为什么还要研究这个?无论如何您都无法修复它们(如果不是这样,那么您可以修改源代码以使用这些工具)。

标签: python performance unix memory memory-leaks


【解决方案1】:

我制作了一个小脚本来获取脚本的内存使用情况,但是,它只能在 osx(肯定)和 linux(很可能)上运行。这只是一种在内部而非外部获取内存的方法,因此您需要执行几行代码来获取其他脚本的 PID 并检测该脚本的内存使用情况。

#imports
import resource
import time

#variables
loops = 1
#gets initial memory usage
memusg = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
#captures initial memory usage
cptrdmemusg = memusg

#loop
while loops == 1:
    #waits for a time, making cpu utilitization non-existant
    time.sleep(300)
    #gets new memory usage
    memusg = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    #detects memory leak. '*3' can be any number.
    if memusg == cptrdmemusg*3:
        print "Memory Leak Detected!"
        print "Memory Usage"+memusg

【讨论】:

    猜你喜欢
    • 2012-07-16
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    相关资源
    最近更新 更多