Sub topic 14
Inspecting and tuning the garbage collector
This chapter assumes you know reference counting and the cyclic collector from the earlier chapters, and that you can use the standard library. The gc module lets you observe the cyclic collector and change when it runs. Most programs never need to change it. Learn to inspect it first, and tune it only when you have measured a problem.
How the collector decides to run
The cyclic collector sorts container objects into generations. New objects start in generation 0. Objects that survive a collection move to an older generation, which is collected less often. The idea is that most objects die young.
Collection is triggered by a counter. Each container allocation adds to the generation 0 count, and each deallocation subtracts from it. When the count passes the generation 0 threshold, a collection runs.
Inspecting the collector
import gc
print(gc.isenabled())
print(gc.get_threshold())
print(gc.get_count())
for generation, stats in enumerate(gc.get_stats()):
print(generation, stats)gc.get_threshold()returns the trigger values. Older versions default to(700, 10, 10). The numbers and the number of generations differ between Python versions, so read them from your interpreter.gc.get_count()returns the current counters.gc.get_stats()returns one dictionary per generation withcollections,collected, anduncollectable.
Watching collections with callbacks
gc.callbacks is a list of functions. The collector calls each one with a phase ("start" or "stop") and an info dictionary. This is a cheap way to see how often collections happen and how long they take.
import gc
import time
class Node:
def __init__(self):
self.other = None
started = 0.0
def report(phase, info):
global started
if phase == "start":
started = time.perf_counter()
else:
elapsed_ms = (time.perf_counter() - started) * 1000
print(f"generation {info['generation']}: "
f"collected {info['collected']} in {elapsed_ms:.3f} ms")
gc.callbacks.append(report)
for _ in range(1000):
a, b = Node(), Node()
a.other, b.other = b, a
gc.collect()
gc.callbacks.remove(report)Calling gc.collect() runs a full collection and returns the number of unreachable objects it found. Pass a generation number to collect only that generation.
Tuning
You can change the collector in three ways.
- Raise the threshold.
gc.set_threshold(50_000, 10, 10)makes collections rarer. Each one has more to scan, but there are fewer of them. This suits programs that build large structures quickly. - Disable it.
gc.disable()stops automatic collection. Reference counting still frees most objects. Only cycles pile up, so callgc.collect()yourself at safe points. - Freeze long-lived objects.
gc.freeze()moves every tracked object into a permanent generation that the collector ignores. Servers that fork worker processes often call it before forking. It keeps the collector from touching shared pages, which avoids copy-on-write memory growth.
import gc
gc.set_threshold(50_000, 10, 10)
print(gc.get_threshold())
gc.freeze()
print(gc.get_freeze_count())
gc.unfreeze()Debugging
gc.set_debug(gc.DEBUG_STATS) prints a summary at each collection. gc.DEBUG_SAVEALL keeps every unreachable object in gc.garbage instead of freeing it. You can then inspect what the cycles contained. Turn debugging off again with gc.set_debug(0). gc.get_objects() lists the tracked objects, and gc.get_referrers(obj) shows what keeps one alive.
Exercise
A batch job builds millions of small objects in a loop and spends noticeable time in the garbage collector. It creates no reference cycles. What is a safe way to reduce that time, and what should you check afterward?
Show answer
Call gc.disable() before the loop, or raise the threshold with gc.setthreshold, and re-enable the collector afterward and call gc.collect() once. Reference counting still frees non-cyclic objects. Afterward, check memory use and gc.getstats() (or call gc.collect() and see whether it returns a large number) to confirm that no cycles were accumulating.