建议使用哪个Python内存分析器?

2024-04-20 11:50:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道Python应用程序的内存使用情况,特别是想知道哪些代码块/部分或对象占用了大部分内存。 谷歌搜索显示一个商业广告是Python Memory Validator(仅限Windows)。

开源的是PySizerHeapy

我没有试过任何人,所以我想知道哪一个是最好的考虑:

  1. 提供了大部分细节。

  2. 我必须对代码做最少或不做任何更改。


Tags: 对象内存代码应用程序windows情况开源validator
3条回答

由于没有人提到过,我将指向我的模块memory_profiler,它能够逐行打印内存使用情况报告,并在Unix和Windows上工作(在最后一个模块上需要psutil)。输出不是很详细,但目标是让您了解代码消耗更多内存的位置,而不是对分配的对象进行详尽的分析。

在用@profile修饰函数并用-m memory_profiler标志运行代码之后,它将逐行打印如下报告:

Line #    Mem usage  Increment   Line Contents
==============================================
     3                           @profile
     4      5.97 MB    0.00 MB   def my_func():
     5     13.61 MB    7.64 MB       a = [1] * (10 ** 6)
     6    166.20 MB  152.59 MB       b = [2] * (2 * 10 ** 7)
     7     13.61 MB -152.59 MB       del b
     8     13.61 MB    0.00 MB       return a

Heapy使用起来相当简单。在代码中的某个时刻,您必须编写以下内容:

from guppy import hpy
h = hpy()
print h.heap()

这将提供如下输出:

Partition of a set of 132527 objects. Total size = 8301532 bytes.
Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
0  35144  27  2140412  26   2140412  26 str
1  38397  29  1309020  16   3449432  42 tuple
2    530   0   739856   9   4189288  50 dict (no owner)

您还可以找出对象被引用的位置,并获得有关该位置的统计信息,但不知何故,该位置上的文档有点稀疏。

还有一个用Tk编写的图形浏览器。

我推荐Dowser。这是非常容易设置,你需要零更改你的代码。您可以通过简单的web界面查看每种类型对象的计数,查看活动对象的列表,查看对活动对象的引用。

# memdebug.py

import cherrypy
import dowser

def start(port):
    cherrypy.tree.mount(dowser.Root())
    cherrypy.config.update({
        'environment': 'embedded',
        'server.socket_port': port
    })
    cherrypy.server.quickstart()
    cherrypy.engine.start(blocking=False)

导入memdebug,然后调用memdebug.start。这就是全部。

我没试过皮西泽或希比。我很感激别人的评论。

更新

以上代码用于CherryPy 2.XCherryPy 3.X方法已被删除,server.quickstart不带blocking标志。所以如果你使用CherryPy 3.X

# memdebug.py

import cherrypy
import dowser

def start(port):
    cherrypy.tree.mount(dowser.Root())
    cherrypy.config.update({
        'environment': 'embedded',
        'server.socket_port': port
    })
    cherrypy.engine.start()

相关问题 更多 >