python的内存调试

python内存增加,内存泄漏调试

gc,objgraph

在调试深度学习(deep Learning)的算法运行过程中发现,在测试阶段,随着图片数据的增加,迭代的过程中造成内存不断的增长,最终导致内存爆满,泄露,和程序奔溃的问题,因此通过调试来发现问题,用到了objgraph, gc等插件来发现问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
### 强制进行垃圾回收  
gc.collect()
# ### 打印出对象数目最多的 50 个类型信息
# objgraph.show_most_common_types(limit=20)
objgraph.show_growth()
# objgraph.show_backrefs(objgraph.by_type('function')[0], max_depth = 10, filename = 'obj.dot')
# objgraph.show_chain(
# objgraph.find_backref_chain(
# objgraph.by_type('_InputList')[0],
# objgraph.is_proper_module
# ),
# filename='obj_chain.dot')
# objgraph.show_backrefs(objgraph.by_type('Tensor')[0], extra_ignore=(id(gc.garbage),), max_depth = 10, filename = 'del_obj.dot')

以此方法生成dot文件之后

1
2
3
4
5
6
7
8
9
import os
import pydotplus
import pydot
os.environ["PATH"] += os.pathsep + 'D:/graphviz/bin'
file_path = "D:/microsoft/ImageCreation/del_obj.dot"
output_path = "D:/microsoft/ImageCreation/del_obj.pdf"
with open(file_path,'r') as f:
graph = pydot.graph_from_dot_data(f.read())
graph[0].write_pdf(output_path)

用pydot将dot转换成pdf可视化观看

另外一种方式,木有尝试过,可能比较简单,直接保存为graph.png格式,省略转换步骤

1
2
3
import objgraph
objgraph.show_growth() # show the growth of the objects
objgraph.show_refs(variableName, filename='graph.png') # show the reference structure of the variable