what are count0, count1 and count2 values returned by the Python gc.get_count()

vy3*_*y32 6 python garbage-collection python-internals

The documentation for python's gc package says this about gc.get_count():

gc.get_count()
    Return the current collection counts as a tuple of (count0, count1, count2).
Run Code Online (Sandbox Code Playgroud)

Here is a sample program:

import gc


if __name__=="__main__":
    print("making some data")
    for k in range(10):
        root = [range(i,1000) for i in range(1,1000)]
    print("len(gc.get_objects):",len(gc.get_objects()))
    print("gc.get_stats:",gc.get_stats())
    print("gc.get_count:",gc.get_count())
Run Code Online (Sandbox Code Playgroud)

Here is the output:

making some data
len(gc.get_objects): 7130
gc.get_stats: [{'collections': 16, 'collected': 99, 'uncollectable': 0}, {'collections': 1, 'collected': 0, 'uncollectable': 0}, {'collections': 0, 'collected': 0, 'uncollectable': 0}]
gc.get_count: (75, 5, 1)
Run Code Online (Sandbox Code Playgroud)

Clearly, count0 = 75, count1=5, and count2=1.

What are count0, count1 and count2?

Bha*_*rel 6

不幸的是,@user10637953 给出的答案和引用的文章都不正确。

count0是自上次垃圾回收以来发生的(跟踪的对象分配 - 释放)。

在达到 gen0 阈值(默认为 700)后的某个时间,将发生 gen0 垃圾收集,并将count0重置。

count1是自上次 gen1 收集以来 gen0 收集的数量。达到阈值(默认为 10)后,将发生第 1 代收集,并将count1重置。

count2是自上次 gen2 收集以来 gen1 收集的数量。达到阈值(默认为 10)后,将发生第 2 代收集,并将count2重置。

您可以通过运行轻松地自己证明这一点gc.collect(gen),并使用查看阈值gc.get_threshold()

有关更多信息,请参阅官方开发指南