Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does gc.collect really release memory?

I am trying to release memory using gc.collect(). But I do not really understand how it works. For example:

enter image description here

Before I run del and gc, the used memory is 58g. After running them, the used memory is still 58. It looks that no memory has been released. I sense gc is different than shutting down python and starting again, which actually release memory.

So I am wondering how to actually release the memory so that I can load other data?

like image 774
Feng Chen Avatar asked Sep 04 '26 09:09

Feng Chen


1 Answers

Depending on your OS, it may not take back the released memory.

You can try out malloc_trim on Linux:

import ctypes

heavy_obj = create_heavy_obj()

# do some jobs

del heavy_obj
ctypes.CDLL("libc.so.6").malloc_trim(0) 
like image 59
June Avatar answered Sep 06 '26 00:09

June