关于 python 内存释放问题的一个疑惑
python 刚运行时只占用 3M 内存
清单 1 :
mt = {}
for i in xrange(10000000):
mt.setdefualt(i, i)
这么时候我机器占用了 450MB 内存
然后我执行: del mt
内存占用 230MB,内存再也不是刚开始执行时候的 3MB 了,这个是为什么呢?
答:试试
import gc
gc.collect()
答:大部分的 malloc 实现和 Python 的对象分配都有用内存池, Python 对象回收不一定会调用 free ,即使调用 free 一些 malloc 实现也不会将内存还给操作系统。
答:整数缓存,每个整个只分配一次内存,但一旦分配了内存一般是不回收的,即使不使用了
答:http://stackoverflow.com/questions/1316767/how-can-i-explicitly-free-memory-in-python
我比较喜欢这个回答 http://effbot.org/pyfaq/why-doesnt-python-release-the-memory-when-i-delete-a-large-object.htm
It ’ s that you ’ ve created 5 million integers simultaneously alive, and each int object consumes 12 bytes. “ For speed ”, Python maintains an internal free list for integer objects. Unfortunately, that free list is both immortal and unbounded in size. floats also use an immortal & unbounded free list.
邮件列表
https://mail.python.org/pipermail/python-bugs-list/2004-October/025619.html
意思就是 python 内部为了速度有一个整数缓存列表,添加了进去之后不知道怎么删除。。。。
答:学习了。 Python 的 GC 大部分时候都工作得很好。
答:Python3 解决了这个问题。
答:这里涉及到整数对象池概念:
python 的 VM 实现中,有大整数和小整数对象池的概念。
首次使用大整数(>257 )时会分配大量内存块, PyIntObject 对象被销毁时,它所占有的内存并不会被释放,归还给系统,而是继续被 Python 保留着
答:对象池不是复用那些整数们,而是为了复用占据的内存空间,避免频繁创建和释放带来很大的性能开销
答:http://stackoverflow.com/questions/32167386/force-garbage-collection-in-python-to-free-memory
0条评论