在分析Python代码的性能时,我们会需要对对象的创建引用销毁全过程进行跟踪,以此来找到需要优化的地方。通常会使用graphviz工具,根据维基百科描述
graphviz是一个由AT&T实验室启动的开源工具包,用于绘制DOT语言脚本描述的图形。
我们还需要使用到Python的包objgraph,根据pypi描述
objgraph is a module that lets you visually explore Python object graphs.
安装
>>> braw install graphviz
>>> pip3 install objgraph
我们模拟一下循环引用导致的内存泄露
import objgraph
class OBJ:
pass
def cycle_reference():
a = OBJ()
b = OBJ()
a.foo = b
b.foo = a
objgraph.show_backrefs(a, max_depth=5, filename='cycle.dot')
cycle_reference()
运行上面代码后会生成cycle.dot文件
digraph ObjectGraph {
node[shape=box, style=filled, fillcolor=white];
o4550717392[fontcolor=red];
o4550717392[label="OBJ\n<__main__.OBJ object at 0x10f3e6fd0>"];
o4550717392[fillcolor="0,0,1"];
o4554241408 -> o4550717392 [label="bar",weight=2];
o4554241408[label="dict\n1 items"];
o4554241408[fillcolor="0,0,0.86"];
o4549819456 -> o4554241408 [label="__dict__",weight=10];
o4549819456[label="OBJ\n<__main__.OBJ object at 0x10f30bc40>"];
o4549819456[fillcolor="0,0,0.72"];
o4549964224 -> o4549819456 [label="foo",weight=2];
o4549964224[label="dict\n1 items"];
o4549964224[fillcolor="0,0,0.58"];
o4550717392 -> o4549964224 [label="__dict__",weight=10];
}
# 生成eps文件
>>> dot -Tps cycle.dot > output.eps
# 生成png文件
>>> dot -Tpng cycle.dot > output.png
明显eps文件更清晰,因为是矢量图
所以如果对图像分辨率有要求的,最好是先生成eps文件再导出为png文件。
可以看到图中红色的为出现问题的对象