Python-建议使用哪个Python内存分析器?
我想知道我的Python应用程序的内存使用情况,尤其想知道哪些代码块/部分或对象消耗了最多的内存。Google搜索显示商用的是Python Memory Validator
(仅限Windows
)。
开源的是PySizer
和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编写的图形浏览器。
-
由于没有人提到它,因此我将指向我的模块
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