gpt4 book ai didi

python - 什么时候在 python 中收集对象垃圾?

转载 作者:太空狗 更新时间:2023-10-29 16:54:02 25 4
gpt4 key购买 nike

什么时候在 python 中收集对象垃圾?什么时候释放内存,回收会影响性能吗?是否可以选择退出或调整 gc 算法?如果可以,如何调整?

最佳答案

什么时候在 python 中收集对象垃圾?

CPython 的源代码中有很多细节:http://svn.python.org/view/python/trunk/Modules/gcmodule.c?revision=81029&view=markup

只要引用计数降为零,对象就会立即被删除。

293 /* Python's cyclic gc should never see an incoming refcount

294 * of 0: if something decref'ed to 0, it should have been

295 * deallocated immediately at that time.

当新对象的数量大于现有对象数量的 25% 时,将触发完全收集。

87 In addition to the various configurable thresholds, we only trigger a

88 full collection if the ratio

89 long_lived_pending / long_lived_total

90 is above a given value (hardwired to 25%).

内存什么时候释放?

我只能找出这些信息。

781 /* Clear all free lists

782 * All free lists are cleared during the collection of the highest generation.

783 * Allocated items in the free list may keep a pymalloc arena occupied.

784 * Clearing the free lists may give back memory to the OS earlier.

785 */

据此,即使您将对象的引用计数降为零,Python 也可能会将您的对象保留在空闲列表中以供回收。我无法明确找到何时进行免费调用以将内存还给操作系统,但我想只要进行收集并且对象未保存在空闲列表中,就会这样做。

收集会影响性能吗?

我听说过的任何重要的垃圾收集器都需要 CPU 和内存才能运行。因此,是的,总会对性能产生影响。您必须进行试验并了解您的垃圾收集器。

需要实时响应的程序我遇到过问题,因为垃圾收集器不允许我控制它们何时运行或运行多长时间。一些特殊情况也会导致内存使用过多,例如 Python 保留空闲列表的诀窍。

关于python - 什么时候在 python 中收集对象垃圾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9449489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com