Skip to content
Advertisement

Python memory release when using a for loop inside a class

I have some troubles after I created a class to process raster images. The class includes different methods for checking DBs and processing the images.

The usage script is super simple:

JavaScript

The method run_extraction() is the following:

JavaScript

The method does several steps for getting an observation for a given variable. The code works, but it doesn’t release memory. Since it’s a loop, with every iteration the used memory increases:

enter image description here

When I close the terminal window executing this process, the memory used drops significantly:

enter image description here

This is happening with a Linux Ubuntu Server LTR 22. When I run the same code in. my laptop (macOS), the memory usage is quite different (with half of server’s RAM):

enter image description here

This didn’t happen with functional programming approach, the memory crashed when I placed the for loop inside a class.

How can I improve the memory management of my class?

Advertisement

Answer

Super simple fix. Cleaning the garbage collector at the end of the loop in the class’ method:

JavaScript

Now the memory usage looks beautiful:

enter image description here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement