Python性能分析器Profile
来源:互联网 发布:数据融合技术的书 编辑:程序博客网 时间:2024/04/29 11:05
Python性能分析器Profile
在使用Python进行开发的过程中,有时候我们需要对Python程序的执行性能进行分析,此时我们就需要用到Python的性能分析工具,这里我就简单说说Python中的profile和pstats库。
下面是一个测试程序
import osdef a(): sum = 0 for i in range(1, 10001): sum += i return sumdef b(): sum = 0 for i in range(1, 100): sum += a() return sumprint b()
此时我们可以使用下面的命令来查看分析结果
python -m cProfile test.py
运行结果如下:
$ python -m cProfile test.py4950495000 202 function calls in 0.040 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.040 0.040 test.py:1(<module>) 99 0.035 0.000 0.040 0.000 test.py:3(a) 1 0.000 0.000 0.040 0.040 test.py:9(b) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 100 0.005 0.000 0.005 0.000 {range}
其中:
- tottime 是函数本身不包括它调用其它函数使用的时间
- cumtime 是函数本身包括它调用其它函数使用的时间
也可以使用下面的命令把结果保存在一个文件里
python -m cProfile -o result test.py
然后使用pstats来格式化显示结果
python -c "import pstats; pstats.Stats('result').sort_stats(-1).print_stats()"
Thu Aug 11 13:20:20 2016 result 202 function calls in 0.037 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.037 0.037 test.py:1(<module>) 99 0.032 0.000 0.036 0.000 test.py:3(a) 1 0.000 0.000 0.037 0.037 test.py:9(b) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 100 0.004 0.000 0.004 0.000 {range}
另外,我们也可以在代码里直接嵌入代码来使用cProfile和pstats模块,这样在程序退出时就会自动生成分析结果并打印,如下:
import osdef a(): sum = 0 for i in range(1, 10001): sum += i return sumdef b(): sum = 0 for i in range(1, 100): sum += a() return sumprint b()import cProfile#cProfile.run("b()")cProfile.run("b()", "result")import pstatspstats.Stats('result').sort_stats(-1).print_stats()
此时运行上面的程序就只要使用下面的命令
python test.py
转载请以链接形式标明本文链接
本文链接:http://blog.csdn.net/kongxx/article/details/52216850
1 0
- Python性能分析器Profile
- python 性能分析器 profile
- Python性能分析器Profile
- Python Profilers性能分析器
- 关于Python Profilers性能分析器
- 关于Python Profilers性能分析器
- Unity 性能分析器Profile中 WaitForTargetFPS 的涵盖
- 【Python】【程序分析器】关于Python Profilers性能分析器
- Python Profile 工具性能分析
- [python]用profile协助程序性能优化
- [python]用profile协助程序性能优化
- [python]用profile协助程序性能优化
- [python]用profile协助程序性能优化
- [python]用profile协助程序性能优化
- [python]用profile协助程序性能优化
- [转]Python Profile 工具性能分析
- [python]用profile协助程序性能优化
- [python]用profile协助程序性能优化
- java代码获得日期之间的天数
- 追踪app崩溃率
- SetSockOpt的使用
- nginx多域名配置
- 链表,类(创建类,模拟商城)
- Python性能分析器Profile
- POJ 3280 Cheapest Palindrome (区间DP)
- iOS 中三种定时器的用法NSTimer、CADisplayLink、GCD
- Linux 查看系统硬件信息(实例详解)
- com.thoughtworks.xstream.converters.ConversionException:
- 驱动模块(driver) 和桩模块(stub)
- [李景山php]每天laravel-20161013|Validator.php-13
- 如何查看iOS已上架app崩溃分布、定位crash发生的行
- 总结Obj-C中+load与+initialize的区别