我正在尝试记录每个函数的内存消耗。我正在使用memory_profiler包,我还得到了包含总内存消耗的最终图表,但不是每个函数,如 this nice tutorial 中所述。
我正在使用以下脚本 test.py
import time
from memory_profiler import profile
#-------------------------------
@profile
def test1():
a = [1] * (10 ** 6)
b = [2] * (2 * 10 ** 7)
del b
return a
#-------------------------------
@profile
def test2():
a = [1] * (10 ** 6)
b = [2] * (2 * 10 ** 7)
del b
return a
#-------------------------------
def main():
l1 = []
l2 = []
for i in range (5) :
print "Iteration", i
l1.append(test1())
l2.append(test2())
time.sleep(1)
if i == 2 :
del l1
l1 = []
#-------------------------------
if __name__ == "__main__":
main()
通过运行它
mprof run test.py
我得到了一些不错的输出,例如
Line # Mem usage Increment Line Contents
================================================
11 46.2 MiB 0.0 MiB @profile
12 def test2():
13 53.8 MiB 7.6 MiB a = [1] * (10 ** 6)
14 206.7 MiB 152.9 MiB b = [2] * (2 * 10 ** 7)
15 53.8 MiB -152.9 MiB del b
16 53.8 MiB 0.0 MiB return a
但是通过绘制它
mprof plot
仅显示总内存消耗,而不显示这些漂亮的小括号,显示链接中所述的不同函数的执行情况。有谁知道如何启用此功能吗?
最佳答案
我正在分析 Django 应用程序。这是我让它发挥作用的方法。
如 @Lukic 所示,从文件中删除 from memory_profiler import profile
。是的,您的编辑器中会出现错误。是的,如果你将其作为普通的 python 文件运行,你会得到一个错误。但是,如果您使用 mprof 命令运行它,它将成功。使用以下命令运行 Django:
mprof run --multiprocess --python python manage.py runserver --noreload
--multiprocess
很重要,因为更新版本的 Django 可能(我认为)甚至在开发服务器上启动多个进程。
--noreload
很重要,否则 Django 将抛出一个错误,因为它首先启动重新加载器进程,然后启动该实际实例(该实例在 @process
上阻塞)装饰器)
在单独的命令窗口中,我可以运行mprofplot
并查看输出。但是,它没有注释任何函数。这是因为在 Django 服务器停止之前注释不会写入 mprof 输出文件。服务器停止后,我可以运行 mprofplot
并查看总体内存利用率和函数运行时间。
希望这会有所帮助 - 我刚刚开始使用 mprof 时遇到了这个问题。
环境: Windows 10, Python 3.5, Django 1.11
引用:https://pypi.org/project/memory-profiler/ (有一个很容易被忽略的关于删除 import 语句的注释,并且没有得到很好的解释)
关于Python 内存分析器绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45549087/