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

查看:88
本文介绍了如何在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 force the Garbage Collector to release unreferenced memory with gc.collect(). Example:

import gc
gc.collect()

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

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