Practical Python Garbage Collection and Memory Analysis: 10 Useful Code Examples
This article explains Python's automatic garbage collection mechanisms, including reference counting and cyclic garbage collection, and presents ten practical code snippets demonstrating how to inspect reference counts, list objects, trace memory usage, and employ profiling tools such as tracemalloc, memory_profiler, pympler, and objgraph to detect leaks and optimize memory usage.
In Python, garbage collection automatically manages memory by detecting objects that are no longer in use and freeing their memory, while memory‑analysis tools help identify leaks and optimize usage.
1. Reference‑counting garbage collection:
import sys
a = [1, 2, 3]
b = a
del a
print(sys.getrefcount(b)) # 输出: 22. Cyclic references and mark‑and‑sweep garbage collection:
import gc
class Node:
def __init__(self):
self.next = None
a = Node()
b = Node()
a.next = b
b.next = a
gc.collect()3. Inspect an object's reference count:
import sys
a = [1, 2, 3]
print(sys.getrefcount(a)) # 输出: 24. Use gc.get_objects() to view current objects:
import gc
objects = gc.get_objects()
print(len(objects)) # 输出: 当前存在的对象数量5. Use gc.get_referents() to see an object's referents:
import gc
a = [1, 2, 3]
b = a
referents = gc.get_referents(b)
print(referents) # 输出: [1, 2, 3]6. Use gc.get_referrers() to see an object's referrers:
import gc
a = [1, 2, 3]
b = a
referrers = gc.get_referrers(a)
print(referrers) # 输出: [b, globals()]7. Use tracemalloc for memory profiling:
import tracemalloc
tracemalloc.start()
# 执行一些代码
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics("lineno")
for stat in top_stats[:10]:
print(stat)8. Use memory_profiler for line‑by‑line memory usage:
from memory_profiler import profile
@profile
def my_function():
# 函数代码
my_function()9. Use pympler.muppy() to list current objects:
from pympler import muppy, summary
all_objects = muppy.get_objects()
sum1 = summary.summarize(all_objects)
summary.print_(sum1)10. Use objgraph to generate object reference graphs:
import objgraph
a = [1, 2, 3]
b = [4, 5, 6]
a.append(b)
b.append(a)
objgraph.show_refs([a], filename="ref_graph.png")These examples demonstrate common applications of garbage collection and memory‑analysis techniques in Python, helping developers understand and optimize program memory usage.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.