国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

談談如何手動釋放Python的內存

2020-02-23 04:11:35
字體:
來源:轉載
供稿:網友

在上篇博客中,提到了對一個腳本進行的多次優化。當時以為已經優化得差不多了,但是當測試人員測試時,我才發現,踩到了Python的一個大坑。

在上文的優化中,對每500個用戶,會進行一些計算并記錄結果在磁盤文件中。原本以為這么做,這些結果就在磁盤文件中了,而不會再繼續占用內存;但實際上,Python的大坑就是Python不會自動清理這些內存。這是由其本身實現決定的。具體原因網上多有文章介紹,這里就不copy了。

本篇博客將貼一個筆者的實驗腳本,用以說明Python確實存在這么一個不釋放內存的現象,另外也提出一個解決方案,即:先del,再顯式調用gc.collect(). 腳本和具體效果見下。

實驗環境一:Win 7, Python 2.7

from time import sleep, time import gc  def mem(way=1):  print time()  for i in range(10000000):   if way == 1:    pass   else: # way 2, 3    del i      print time()  if way == 1 or way == 2:   pass  else: # way 3   gc.collect()  print time()    if __name__ == "__main__":  print "Test way 1: just pass"  mem(way=1)  sleep(20)  print "Test way 2: just del"  mem(way=2)  sleep(20)  print "Test way 3: del, and then gc.collect()"  mem(way=3)  sleep(20)   

運行結果如下:

Test way 1: just pass 1426688589.47 1426688590.25 1426688590.25 Test way 2: just del 1426688610.25 1426688611.05 1426688611.05 Test way 3: del, and then gc.collect() 1426688631.05 1426688631.85 1426688631.95 

對于way 1和way 2,結果是完全一樣的,程序內存消耗峰值是326772KB,在sleep 20秒時,內存實時消耗是244820KB;

對于way 3,程序內存消耗峰值同上,但是sleep時內存實時消耗就只有6336KB了。

實驗環境二: Ubuntu 14.10, Python 2.7.3

運行結果:

Test way 1: just pass 1426689577.46 1426689579.41 1426689579.41 Test way 2: just del 1426689599.43 1426689601.1 1426689601.1 Test way 3: del, and then gc.collect() 1426689621.12 1426689622.8 1426689623.11 
ubuntu@my_machine:~$ ps -aux | grep test_mem Warning: bad ps syntax, perhaps a bogus '-'? See http://procps.sf.net/faq.html ubuntu 9122 10.0 6.0 270916 245564 pts/1 S+ 14:39 0:03 python test_mem.py ubuntu 9134 0.0 0.0 8104 924 pts/2 S+ 14:40 0:00 grep --color=auto test_mem ubuntu@my_machine:~$ ps -aux | grep test_mem Warning: bad ps syntax, perhaps a bogus '-'? See http://procps.sf.net/faq.html ubuntu 9122 10.0 6.0 270916 245564 pts/1 S+ 14:39 0:03 python test_mem.py ubuntu 9134 0.0 0.0 8104 924 pts/2 S+ 14:40 0:00 grep --color=auto test_mem ubuntu@my_machine:~$ ps -aux | grep test_mem Warning: bad ps syntax, perhaps a bogus '-'? See http://procps.sf.net/faq.html ubuntu 9122 11.6 0.1 30956 5608 pts/1 S+ 14:39 0:05 python test_mem.py 

結論:

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宁乡县| 卓资县| 建平县| 娄底市| 吉木萨尔县| 丹寨县| 惠水县| 合水县| 清水县| 宁乡县| 定远县| 拜城县| 曲靖市| 台东县| 井陉县| 南丹县| 丹寨县| 香格里拉县| 荣昌县| 汤阴县| 美姑县| 文山县| 恩施市| 平陆县| 云龙县| 广昌县| 恭城| 黔东| 友谊县| 澎湖县| 马公市| 庆云县| 京山县| 瑞昌市| 江源县| 滦南县| 曲麻莱县| 陆川县| 宝兴县| 永仁县| 化州市|