如何在 Python 中显式释放内存? [英] How can I explicitly free memory in Python?

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

问题描述

我编写了一个 Python 程序,该程序作用于一个大型输入文件,以创建代表三角形的几百万个对象.算法是:

I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is:

  1. 读取输入文件
  2. 处理文件并创建一个三角形列表,由它们的顶点表示
  3. 以OFF格式输出顶点:顶点列表后跟三角形列表.三角形由顶点列表中的索引表示

在打印出三角形之前打印出完整的顶点列表的 OFF 要求意味着我必须在将输出写入文件之前将三角形列表保存在内存中.与此同时,由于列表的大小,我收到了内存错误.

The requirement of OFF that I print out the complete list of vertices before I print out the triangles means that I have to hold the list of triangles in memory before I write the output to file. In the meanwhile I'm getting memory errors because of the sizes of the lists.

告诉 Python 我不再需要某些数据并且可以释放它的最佳方法是什么?

What is the best way to tell Python that I no longer need some of the data, and it can be freed?

推荐答案

根据Python官方文档,您可以使用 gc.collect() 显式调用垃圾收集器来释放未引用的内存.示例:

According to Python Official Documentation, you can explicitly invoke the Garbage Collector to release unreferenced memory with gc.collect(). Example:

import gc

gc.collect()

您应该在使用 del 标记要丢弃的内容后执行此操作:

You should do that after marking what you want to discard using del:

del my_array
del my_object
gc.collect()

这篇关于如何在 Python 中显式释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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