python性能分析工具:cProfile使用

来源:互联网 发布:45号钢原料重量算法 编辑:程序博客网 时间:2024/05/19 16:38

在进行python开发时需要对python脚本的性能分析,以便对python脚本进行优化,下面使用cProfile和 pstats对python脚本性能分析。

cProfile思路
1.使用cProfile模块生成脚本执行的统计信息文件
2.使用pstats格式化统计信息,并根据需要做排序分析处理

1.使用cProfile模块生成脚本执行的统计信息文件
python -m cProfile -o /jtitsm/01_shipper/cProfile_read_xml.txt read_xml.py /jtitsm/TEST/wbmh_1/20171017 /soft/omc_bak/xml/test_1/20171017 /jtitsm/01_shipper_test/logs/file2tcp_xml.log.20171017

参数说明:
使用模块当做脚本运行:-m cProfile
输出参数:-o /jtitsm/01_shipper/cProfile_read_xml.txt
测试的python脚本:read_xml.py
其余为python脚本的输入参数

2.python命令行查看统计信息。
执行python:

import pstatsp=pstats.Stats('/jtitsm/01_shipper/cProfile_read_xml.txt')p.print_stats()#根据调用次数排序p.sort_stats('calls').print_stats()#根据调用总时间排序p.sort_stats('cumulative').print_stats()

*Stats类(pstats.Stats)说明
strip_dirs() 用以除去文件名前的路径信息。
add(filename,[…]) 把profile的输出文件加入Stats实例中统计
dump_stats(filename) 把Stats的统计结果保存到文件
sort_stats(key,[…]) 最重要的一个函数,用以排序profile的输出
reverse_order() 把Stats实例里的数据反序重排
print_stats([restriction,…]) 把Stats报表输出到stdout
print_callers([restriction,…]) 输出调用了指定的函数的函数的相关信息
print_callees([restriction,…]) 输出指定的函数调用过的函数的相关信息

sort_stats支持以下参数:
参数 含义
‘calls’ call count
‘cumulative’ cumulative time
‘file’ file name
‘filename’ file name
‘module’ module name
‘ncalls’ call count
‘pcalls’ primitive call count
‘line’ line number
‘name’ function name
‘nfl’ name/file/line
‘stdname’ standard name
‘time’ internal time
‘tottime’ internal time

*一个比较典型的输出结果:
197 function calls (192 primitive calls) in 0.002 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.001 0.001 :1()
1 0.000 0.000 0.001 0.001 re.py:212(compile)
1 0.000 0.000 0.001 0.001 re.py:268(_compile)
1 0.000 0.000 0.000 0.000 sre_compile.py:172(_compile_charset)
1 0.000 0.000 0.000 0.000 sre_compile.py:201(_optimize_charset)
4 0.000 0.000 0.000 0.000 sre_compile.py:25(_identityfunction)
3/1 0.000 0.000 0.000 0.000 sre_compile.py:33(_compile)
输出结果说明:

共有197次函数调用,原始调用为192次,原始调用说明不包含递归调用。
以standard name进行排序。3/1表示发生了递归调用,1为原始调用次数,3为递归调用次数
ncalls 函数的被调用次数
tottime 函数总计运行时间,除去函数中调用的函数运行时间
percall 函数运行一次的平均时间,等于tottime/ncalls
cumtime 函数总计运行时间,含调用的函数运行时间
percall 函数运行一次的平均时间,等于cumtime/ncalls
filename:lineno(function) 函数所在的文件名,函数的行号,函数名

原创粉丝点击