Python中的可用内存 [英] Free memory in Python

查看:175
本文介绍了Python中的可用内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在python中释放列表的部分内存? 我可以通过以下方式做到这一点:

How can I free part of list's memory in python? Can I do it in the following manner:

del list[0:j]  

或对于单个列表节点:

del list[j] 

Mark:我的脚本分析了巨大的列表并创建了巨大的输出,这就是为什么我需要立即分配内存.

Mark: My script analyzes huge lists and creates huge output that is why I need immediate memory deallocation.

推荐答案

您无法真正在Python中手动释放内存.

You cannot really free memory manually in Python.

使用del会减少对象的引用计数.一旦该引用计数达到零,该对象将在运行垃圾收集器时被释放.

Using del decreases the reference count of an object. Once that reference count reaches zero, the object will be freed when the garbage collector is run.

因此,您最好的办法是在del处理完一堆对象之后手动运行gc.collect().

So the best you can do is to run gc.collect() manually after del-ing a bunch of objects.

在这些情况下,最好的建议通常是尝试更改您的算法.例如,使用发电机而不是Thijs在评论中建议的列表.

In these cases the best advice is usually to try and change your algorithms. For example use a generator instead of a list as Thijs suggests in the comments.

另一种策略是将硬件投入到问题上(购买更多的RAM).但这通常具有财务和技术限制. :-)

The other strategy is to throw hardware at the problem (buy more RAM). But this generally has financial and technical limits. :-)

这篇关于Python中的可用内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆