这篇文章给大家介绍概要性能分析工具怎么在Python中使用,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
分析器是Python自带的一组程序,能够描述程序运行时候的性能,并提供各种统计帮助用户定位程序的性能瓶颈.Python标准模块提供三种分析器:cProfile,概要文件以及高手。
概要文件的使用非常简单,只需要在使用之前进行导入即可,也可以在命令行中使用。
<强>使用配置文件强>
测试示例:
import 概要文件 def (): sum 才能=0 for 才能小姐:拷贝范围(1,10001): ,,sum +=,我 return 才能;和 def b (): sum 才能=0 for 才能小姐:拷贝范围(1,100): ,,,sum +=, () return 才能;和 if __name__ ==,“__main__": profile.run才能(“b ()“)
输出结果:
,,,& lt; br 过滤数据=癴iltered"祝辞,104,function calls 拷贝0.094秒 , Ordered 由:standard 名称 , ncalls tottime  percall cumtime percall 文件名:lineno(函数) ,,1,,,0.000,0.000,,0.094,,0.094,:0(执行) ,,1,,,0.000,0.000,,0.000,,0.000,:0 (setprofile) ,,1,,,0.000,0.000,,0.094,,0.094,& lt; string>: 1 (& lt; module>) ,,1,,,0.000,0.000,,0.094,,0.094,简介:0 (b ()) 0,,,,0.000,,,,,,,0.000,,,,,简介: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)
其中输出每列的具体解释如下:
●ncalls:表示函数调用的次数;
●tottime:表示指定函数的总的运行时间,除掉函数中调用子函数的运行时间,
●percall:(第一个percall)等于tottime/ncalls;
●cumtime:表示该函数及其所有子函数的调用运行的时间,即函数开始调用到返回的时间,
●percall:(第二个percall)即函数运行一次的平均时间,等于cumtime/ncalls;
●文件名:lineno(功能):每个函数调用的具体信息;
如果需要将输出以日志的形式保存,只需要在调用的时候加入另外一个参数。如profile.run (“profileTest ()”,“testprof”)。
<>强命令行强>
如果我们不想在程序中调用轮廓库使用,可以在命令行使用命令。
import 操作系统 def (): sum 才能=0 for 才能小姐:拷贝范围(1,10001): ,,sum +=,我 return 才能;和 def b (): sum 才能=0 for 才能小姐:拷贝范围(1,100): ,,,sum +=, () return 才能;和 print b ()
运行命令查看性能分析结果
python -m cProfile 测试。py
将性能分析结果保存到结果文件
python -m cProfile -o result 测试。py
使用pstats来格式化显示结果
python -c “import pstats;, p=pstats.Stats (& # 39; reslut);, p.print_stats ()“; python -c “import pstats, p=pstats.Stats(& # 39;结果# 39;);,p.sort_stats(& # 39;时间# 39;).print_stats ()
sort_stats支持以下参数:
调用,累积的,文件,行,模块,名字,nfl, pcalls, stdname,时间
测试示例:在代码中直接使用配置文件与数据
import 操作系统 def (): sum =0 for 小姐:拷贝范围(1,10001): sum +=我 return 和 def b (): sum =0 for 小姐:拷贝范围(1,100): sum +=, () return 和 print b () import cProfile #, cProfile.run (“b ()“) “cProfile.run (“b (),,“result") import pstats pstats.Stats(& # 39;结果# 39;).sort_stats (1) .print_stats ()
关于概要性能分析工具怎么在Python中使用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看的到。