加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何手动释放Python的内存

发布时间:2020-12-17 01:24:02 所属栏目:Python 来源:网络整理
导读:p style="color:rgb(51,51,51);font-family:Arial;font-size:14px;"在上篇博客中,提到了对一个脚本进行的多次优化。当时以为已经优化得差不多了,但是当a href="http://lib.csdn.net/base/softwaretest" rel="nofollow" class="replace_word" title="软件测

<p style="color:rgb(51,51,51);font-family:Arial;font-size:14px;">在上篇博客中,提到了对一个脚本进行的多次优化。当时以为已经优化得差不多了,但是当<a href="http://lib.csdn.net/base/softwaretest" rel="nofollow" class="replace_word" title="软件测试知识库" style="color:rgb(223,52,52);text-decoration:none;font-weight:bold;">测试人员测试时,我才发现,踩到了<a href="http://lib.csdn.net/base/python" rel="nofollow" class="replace_word" title="Python知识库" style="color:rgb(223,52);text-decoration:none;font-weight:bold;">Python的一个大坑。


<p style="color:rgb(51,51);font-family:Arial;font-size:14px;">在上文的优化中,对每500个用户,会进行一些计算并记录结果在磁盘文件中。原本以为这么做,这些结果就在磁盘文件中了,而不会再继续占用内存;但实际上,Python的大坑就是Python不会自动清理这些内存。这是由其本身实现决定的。具体原因网上多有文章介绍,这里就不copy了。


<p style="color:rgb(51,51);font-family:Arial;font-size:14px;">本篇博客将贴一个笔者的实验脚本,用以说明Python确实存在这么一个不释放内存的现象,另外也提出一个解决方案,即:先del,再显式调用gc.collect(). 脚本和具体效果见下。


<p style="color:rgb(51,51);font-family:Arial;font-size:14px;">


<p style="color:rgb(51,51);font-family:Arial;font-size:14px;"><span style="color:rgb(51,102,255);">实验环境一:Win 7, Python 2.7


<p style="color:rgb(51,51);font-family:Arial;font-size:14px;">


<div class="dp-highlighter bg_python" style="font-family:Consolas,'Courier New',Courier,mono,serif;background-color:rgb(231,229,220);color:rgb(51,51);">
<div class="bar">
<div class="tools" style="font-size:9px;line-height:normal;font-family:Verdana,Geneva,Arial,Helvetica,sans-serif;color:#C0C0C0;background-color:rgb(248,248,248);border-left:3px solid rgb(108,226,108);">
[python]?<a href="http://blog.csdn.net/nirendao/article/details/44426201/#" rel="nofollow" class="ViewSource" title="view plain" style="color:rgb(160,160,160);text-decoration:none;background-color:inherit;border:none;font-size:9px;display:inline-block;width:16px;text-indent:-2000px;">view
plain?<a href="http://blog.csdn.net/nirendao/article/details/44426201/#" rel="nofollow" class="CopyToClipboard" title="copy" style="color:rgb(160,160);text-decoration:none;background-color:inherit;border:none;font-size:9px;display:inline-block;width:16px;text-indent:-2000px;">copy
<div style="width:18px;z-index:99;">

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读