内存泄漏python

可能的原因

some low level C library is leaking
更低级别的 C 包泄漏

your Python code have global lists or dicts that grow over time, and you forgot to remove the objects after use
程序中的全局变量没有释放

there are some reference cycles in your app
存在循环引用

排查内存泄露的小代码


from collections import defaultdict
from gc import get_objects

before = defaultdict(int)
after = defaultdict(int)

for i in get_objects():
    before[type(i)] += 1

# your code 

for i in get_objects():
    after[type(i)] += 1

print([(k, after[k] - before[k]) for k in after if after[k] - before[k]])


多线程

  • 排查是否存在没有释放的连接

工具

memory-profiler objgraph

Buy me a 肥仔水!