首页 技术 正文
技术 2022年11月11日
0 收藏 954 点赞 5,087 浏览 1186 个字

Python标准库中提供了三种用来分析程序性能的模块,分别是cProfile, profile和hotshot,另外还有一个辅助模块stats。这些模块提供了对Python程序的确定性分析功能,同时也提供了相应的报表生成工具,方便用户快速地检查和分析结果。 

    这三个性能分析模块的介绍如下:

    cProfile:基于lsprof的用C语言实现的扩展应用,运行开销比较合理,适合分析运行时间较长的程序,推荐使用这个模块;

    profile:纯Python实现的性能分析模块,接口和cProfile一致。但在分析程序时增加了很大的运行开销。不过,如果你想扩展profiler的功能,可以通过继承这个模块实现;

    hotshot:一个试验性的C模块,减少了性能分析时的运行开销,但是需要更长的数据后处理的次数。目前这个模块不再被维护,有可能在新版本中被弃用。

2种方式使用:

cProfile.run('func(arg)','filename.txt')     # 调优函数,在脚本中使用
python -m cProfile myscript.py [-o filename.txt] # 调优脚本,在命令行使用 -o表示输出到文件

输出解释

         7 function calls in 0.088 seconds   Ordered by: standard name   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
1 0.003 0.003 0.088 0.088 <string>:1(<module>)
1 0.000 0.000 0.085 0.085 cProfile模块.py:14(f3)
1 0.010 0.010 0.010 0.010 cProfile模块.py:15(<listcomp>)
1 0.015 0.015 0.015 0.015 cProfile模块.py:17(<listcomp>)
1 0.000 0.000 0.088 0.088 {built-in method builtins.exec}
1 0.060 0.060 0.060 0.060 {built-in method builtins.sorted}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}

共有 7次函数调用,耗时0.088秒,原始调用为 0次,原始调用代表不包含递归调用。

ncalls 函数的被调用次数

tottime 函数总计运行时间,除去函数中调用的函数运行时间

percall 函数运行一次的平均时间,等于tottime/ncalls

cumtime 函数总计运行时间,含调用的函数运行时间

percall 函数运行一次的平均时间,等于cumtime/ncalls

filename:lineno(function) 函数所在的文件名,函数的行号,函数名

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,991
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,506
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,349
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,134
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,766
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,844