Python性能分析工具Profile使用实例
本文介绍Python内置的性能分析工具Profile及其子模块cProfile和hotshot的使用方法。通过示例代码演示如何在程序中调用Profile,以及如何利用命令行参数进行性能测试。文章详细解析了输出结果中ncalls、tottime、percall、cumtime等关键指标的含义,并展示了如何使用pstats模块对分析结果进行排序和格式化显示,帮助开发者快速定位代码瓶颈。
Python性能分析工具Profile使用实例
本文主要介绍Python性能分析工具Profile的使用实例。文中通过详细的示例代码进行说明,对读者的学习或工作具有参考价值,建议读者仔细阅读并参考相关代码。
Python内置性能分析工具概述
代码优化的前提在于明确性能瓶颈所在,即了解程序运行的主要时间消耗点。对于较为复杂的代码,借助工具进行定位是必要的。Python内置了丰富的性能分析工具,包括profile、cProfile与hotshot等。其中,Profiler是Python自带的一组程序,能够描述程序运行时的性能状况,并提供各类统计数据以帮助用户定位性能瓶颈。Python标准模块提供了三种Profiler:cProfile、profile以及hotshot。
Profile的基本使用方法
使用profile非常简单,只需在使用前进行import导入即可,也可以在命令行中直接使用。
使用Profile进行代码测试
使用Profile
测试示例:
import profile
def a():
sum = 0
for i in range(1, 10001):
sum += i
return sum
def b():
sum = 0
for i in range(1, 100):
sum += a()
return sum
if __name__ == "__main__":
profile.run("b()")
输出结果:
<br data-filtered="filtered"> 104 function calls in 0.094 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.094 0.094 :0(exec)
1 0.000 0.000 0.000 0.000 :0(setprofile)
1 0.000 0.000 0.094 0.094 <string>:1(<module>)
1 0.000 0.000 0.094 0.094 profile:0(b())
0 0.000 0.000 profile:0(profiler)
99 0.094 0.001 0.094 0.001 test.py:15(a)
1 0.000 0.000 0.094 0.094 test.py:21(b)
Profile输出结果详解
其中输出每列的具体解释如下:
●ncalls:表示函数调用的次数;
●tottime:表示指定函数的总的运行时间,不包括函数中调用子函数的运行时间;
●percall:(第一个percall)等于tottime除以ncalls;
●cumtime:表示该函数及其所有子函数的调用运行的时间,即从函数开始调用到返回的时间;
●percall:(第二个percall)即函数运行一次的平均时间,等于cumtime除以ncalls;
●filename:lineno(function):每个函数调用的具体信息;
保存Profile输出日志
如果需要将输出以日志的形式保存,只需在调用时加入另一个参数。例如:profile.run("profileTest()","testprof")。
命令行使用Profile
命令行
如果我们不想在程序中调用profile库,可以在命令行中使用命令。
import os
def a():
sum = 0
for i in range(1, 10001):
sum += i
return sum
def b():
sum = 0
for i in range(1, 100):
sum += a()
return sum
print b()
运行命令查看性能分析结果
python -m cProfile test.py
将性能分析结果保存到result文件
python -m cProfile -o result test.py
使用pstats格式化显示结果
使用pstats来格式化显示结果
python -c "import pstats; p=pstats.Stats('reslut); p.print_stats()"
python -c "import pstats; p=pstats.Stats('result'); p.sort_stats('time').print_stats()
sort_stats支持以下参数:
calls, cumulative, file, line, module, name, nfl, pcalls, stdname, time
测试示例:在代码中直接使用profile与stats
import os
def a():
sum = 0
for i in range(1, 10001):
sum += i
return sum
def b():
sum = 0
for i in range(1, 100):
sum += a()
return sum
print b()
import cProfile# cProfile.run("b()")
cProfile.run("b()", "result")
import pstats
pstats.Stats('result').sort_stats(-1).print_stats()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









