我想知道我的 Python 应用程序的内存使用情况,尤其想知道哪些代码块 / 部分或对象消耗了最多的内存。 Google 搜索显示商用的是Python Memory Validator (仅限 Windows)。
我没有尝试过任何人,所以我想知道哪个是最好的考虑因素:
提供大多数细节。
我不必对代码进行最少的更改,也可以不做任何更改。
我的模块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 aguppy3 的使用非常简单。在代码中的某些时候,您必须编写以下代码:
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 编写的图形浏览器。
对于 Python 2.x,请使用Heapy 。
我推荐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。就这样。
我没有尝试过 PySizer 或 Heapy。我会很感激别人的评论。
更新
上面的代码适用于CherryPy 2.X , CherryPy 3.X , server.quickstart方法已被删除, engine.start不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()