Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I explicitly free memory in 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. read an input file
  2. process the file and create a list of triangles, represented by their vertices
  3. output the vertices in the OFF format: a list of vertices followed by a list of triangles. The triangles are represented by indices into the list of vertices

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.

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

like image 657
Nathan Fellman Avatar asked Aug 22 '09 19:08

Nathan Fellman


People also ask

How do I free up memory in Python?

to clear Memory in Python just use del. By using del you can clear the memory which is you are not wanting. By using del you can clear variables, arrays, lists etc.

Does Python automatically free memory?

Memory management Unlike many other languages, Python does not necessarily release the memory back to the Operating System. Instead, it has a dedicated object allocator for objects smaller than 512 bytes, which keeps some chunks of already allocated memory for further use in the future.

Which is the correct way to deallocate memory in Python?

Python's memory allocation and deallocation method is automatic. The user does not have to preallocate or deallocate memory by hand as one has to when using dynamic memory allocation in languages such as C or C++. Python uses two strategies for memory allocation reference counting and garbage collection.

Does Python free memory after function call?

If you don't manually free() the memory allocated by malloc() , it will never get freed. Python, in contrast, tracks objects and frees their memory automatically when they're no longer used. But sometimes that fails, and to understand why you need to understand how it tracks them.


1 Answers

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

import gc  gc.collect() 

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

del my_array del my_object gc.collect() 
like image 136
Havenard Avatar answered Sep 24 '22 17:09

Havenard