Python性能分析工具Profile使用实例
这篇文章主要介绍了Python性能分析工具Profile使用实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
代码优化的前提是需要了解性能瓶颈在什么地方,程序运行的主要时间是消耗在哪里,对于比较复杂的代码可以借助一些工具来定位,python内置了丰富的性能分析工具,如profile,cProfile与hotshot等。其中Profiler是python自带的一组程序,能够描述程序运行时候的性能,并提供各种统计帮助用户定位程序的性能瓶颈。Python标准模块提供三种profilers:cProfile,profile以及hotshot。
profile的使用非常简单,只需要在使用之前进行import即可,也可以在命令行中使用。
使用Profile
测试示例:
importprofile defa(): sum=0 foriinrange(1,10001): sum+=i returnsum defb(): sum=0 foriinrange(1,100): sum+=a() returnsum if__name__=="__main__": profile.run("b()")
输出结果:
104functioncallsin0.094seconds Orderedby:standardname ncallstottimepercallcumtimepercallfilename:lineno(function) 10.0000.0000.0940.094:0(exec) 10.0000.0000.0000.000:0(setprofile) 10.0000.0000.0940.094 :1( ) 10.0000.0000.0940.094profile:0(b()) 00.0000.000profile:0(profiler) 990.0940.0010.0940.001test.py:15(a) 10.0000.0000.0940.094test.py:21(b)
其中输出每列的具体解释如下:
●ncalls:表示函数调用的次数;
●tottime:表示指定函数的总的运行时间,除掉函数中调用子函数的运行时间;
●percall:(第一个percall)等于tottime/ncalls;
●cumtime:表示该函数及其所有子函数的调用运行的时间,即函数开始调用到返回的时间;
●percall:(第二个percall)即函数运行一次的平均时间,等于cumtime/ncalls;
●filename:lineno(function):每个函数调用的具体信息;
如果需要将输出以日志的形式保存,只需要在调用的时候加入另外一个参数。如profile.run(“profileTest()”,”testprof”)。
命令行
如果我们不想在程序中调用profile库使用,可以在命令行使用命令。
importos defa(): sum=0 foriinrange(1,10001): sum+=i returnsum defb(): sum=0 foriinrange(1,100): sum+=a() returnsum printb()
运行命令查看性能分析结果
python-mcProfiletest.py
将性能分析结果保存到result文件
python-mcProfile-oresulttest.py
使用pstats来格式化显示结果
python-c"importpstats;p=pstats.Stats('reslut);p.print_stats()" python-c"importpstats;p=pstats.Stats('result');p.sort_stats('time').print_stats()
sort_stats支持以下参数:
calls,cumulative,file,line,module,name,nfl,pcalls,stdname,time
测试示例:在代码中直接使用profile与stats
importos defa(): sum=0 foriinrange(1,10001): sum+=i returnsum defb(): sum=0 foriinrange(1,100): sum+=a() returnsum printb() importcProfile#cProfile.run("b()") cProfile.run("b()","result") importpstats pstats.Stats('result').sort_stats(-1).print_stats()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。