【Py】使用graphviz可视化对象引用关系

在分析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文件。

可以看到图中红色的为出现问题的对象

参考:https://graphviz.org/download/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值