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.py
下
get_im_blob
等函數占用內存不斷增大,每檢測一副圖像,該函數增加6-10MB內存開銷。但奇怪的是用guppy查看前十個變量,并沒有發現哪個變量有明顯的內存增大跡象。于是猜測可能是每張圖像推理后,推理的結果bbox,label,img等數據保存在了內存中,這樣方便所有圖像推理結束后,
plt.show().
于是修改程序,每張圖像推理后,
plt.show()
一下。用
memory_profiler
發現內存不再繼續增大,interesting!其實把
plt.show()
改成
plt.close()也
可以防止內存不斷增大。具體原因肯定是python 的內存回收機制規則導致的。
總結
以上所述是小編給大家介紹的python內存監控工具memory_profiler和guppy的用法詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
