Python性能分析器Profile
2017-10-20 17:47
357 查看
参考:http://blog.csdn.net/kongxx/article/details/52216850
在使用Python进行开发的过程中,有时候我们需要对Python程序的执行性能进行分析,此时我们就需要用到Python的性能分析工具,这里我就简单说说Python中的profile和pstats库。
下面是一个测试程序
2
3
4
5
6
7
8
9
10
11
12
13
14
15
此时我们可以使用下面的命令来查看分析结果
运行结果如下:
2
3
4
5
6
7
8
9
10
11
12
其中:
- tottime 是函数本身不包括它调用其它函数使用的时间
- cumtime 是函数本身包括它调用其它函数使用的时间
也可以使用下面的命令把结果保存在一个文件里
然后使用pstats来格式化显示结果
2
3
4
5
6
7
8
9
10
11
12
另外,我们也可以在代码里直接嵌入代码来使用cProfile和pstats模块,这样在程序退出时就会自动生成分析结果并打印,如下:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
此时运行上面的程序就只要使用下面的命令
在使用Python进行开发的过程中,有时候我们需要对Python程序的执行性能进行分析,此时我们就需要用到Python的性能分析工具,这里我就简单说说Python中的profile和pstats库。
下面是一个测试程序
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()1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
此时我们可以使用下面的命令来查看分析结果
python -m cProfile test.py1
运行结果如下:
$ python -m cProfile test.py 4950495000 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}1
2
3
4
5
6
7
8
9
10
11
12
其中:
- tottime 是函数本身不包括它调用其它函数使用的时间
- cumtime 是函数本身包括它调用其它函数使用的时间
也可以使用下面的命令把结果保存在一个文件里
python -m cProfile -o result test.py1
然后使用pstats来格式化显示结果
python -c "import pstats; pstats.Stats('result').sort_stats(-1).print_stats()"1
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}1
2
3
4
5
6
7
8
9
10
11
12
另外,我们也可以在代码里直接嵌入代码来使用cProfile和pstats模块,这样在程序退出时就会自动生成分析结果并打印,如下:
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()1
import cProfile
#cProfile.run("b()")
cProfile.run("b()", "result")
import pstats
pstats.Stats('result').sort_stats(-1).print_stats()
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
此时运行上面的程序就只要使用下面的命令
python test.py1
相关文章推荐
- python性能分析--cProfile
- cProfile——Python性能分析工具
- python_性能分析profile
- [转]Python Profile 工具性能分析
- 使用 profile 进行python代码性能分析
- 利用PyCharm的Profile工具进行Python性能分析
- Python程序性能分析模块----------cProfile
- python 性能分析器 profile
- Python程序的性能分析指南
- 常用排序算法的python实现和性能分析
- python性能分析工具:cProfile使用
- 转帖:Python应用性能分析指南
- 【脚本语言系列】关于Python性能分析工具timeit, 你需要知道的事
- 常用排序算法的python实现和性能分析
- MySQL性能分析工具profile使用教程
- [python]用profile协助程序性能优化
- Python性能分析 (Profiling)
- [python]用profile协助程序性能优化
- [python]用profile协助程序性能优化
- Python判断列表是否已排序的各种方法及其性能分析