Clear RAM (Garbage Collection) in Python

Clear RAM usage at run time in Python with this function and optionally print the remining RAM usage. Helpful when executing code in loops which cnsume a large amoount of RAM.

About

We make use of the built-in Garbage Collection library for the removal of objects from RAM. There are other methods for clearing RAM in Python which are explained in detail here – a recommended read.

Code

If you would rather not use the below function then you can simply add the following code as u see fit.

Or you can use this function in you code and optionally print the current RAM usage of the process/script after garbage collection is complete.

Explnation

After importing required libraries we call gc.collection() to run a full collection. Then if specified we print the remaining RAMusage with the psutil library.

Links

About the author

Leave a Reply

Your email address will not be published. Required fields are marked *