温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python内存监控工具memory_profiler和guppy的用法详解

发布时间:2020-08-21 19:44:58 来源:脚本之家 阅读:1431 作者:一江明澈的水 栏目:开发技术

python2.7在内存管理上相比python3还是有些坑的,其释放后的内存仍然保留在python的内存池中,不被系统所用。python循环引用的变量不会被回收,这会导致程序越运行,占用的内存越大。我在跑py-faster-rcnn的demo时,基本上跑2000张图像,16g内存就要爆了。于是尝试用python的内存监控工具来调试程序,找到不能膨胀的变量,然后del之,再手动回收内存gc.collec()

下面是我用的两个内存监视工具,一个是按每行代码查看内存占用的工具memory_profiler,一个是查看占用内存前十位变量的工具guppy。

1. memory_profiler

首先是安装:

pip install -U memory_profiler

然后用profile修饰想要查看的函数名:如:

@profile
def my_func():
 a = [1] * (10 ** 6)
 b = [2] * (2 * 10 ** 7)
 del b
 return a

if __name__ == '__main__':
 my_func()

输出结果:

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

memory_profiler功能强大,更多功能可以看官网这里

2. guppy

首先安装:

pip install guppy

然后import下

from guppy import hpy
hxx = hpy()
heap = hxx.heap()
byrcs = hxx.heap().byrcs;

在主程序下增加:

print(heap)

输出示例:

Index Count %  Size % Cumulative % Kind (class / dict of class)
  0 10124 22 81944416 95 81944416 95 list
  1 16056 34 1325464 2 83269880 96 str
  2 9147 20 745616 1 84015496 97 tuple
  3 102 0 366480 0 84381976 98 dict of module
  4 287 1 313448 0 84695424 98 dict of type
  5 2426 5 310528 0 85005952 98 types.CodeType
  6 2364 5 283680 0 85289632 99 function
  7 287 1 256960 0 85546592 99 type
  8 169 0 192088 0 85738680 99 dict (no owner)
  9 123 0 142728 0 85881408 99 dict of class

可以看到第一个list占了95%的内存,若print(heap)在主程序的循环中,可以查看每次循环后的变量内存占用情况。

输入以下命令,查看这个占内存最大的list中的数据类型:
byrcs[0].byid

最后测试后发现,test.pyget_im_blob等函数占用内存不断增大,每检测一副图像,该函数增加6-10MB内存开销。但奇怪的是用guppy查看前十个变量,并没有发现哪个变量有明显的内存增大迹象。于是猜测可能是每张图像推理后,推理的结果bbox,label,img等数据保存在了内存中,这样方便所有图像推理结束后,plt.show().于是修改程序,每张图像推理后,plt.show()一下。用memory_profiler发现内存不再继续增大,interesting!其实把plt.show()改成plt.close()也可以防止内存不断增大。具体原因肯定是python 的内存回收机制规则导致的。

总结

以上所述是小编给大家介绍的python内存监控工具memory_profiler和guppy的用法详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI