性能分析器主要有两个模块:cProfile、line_profiler、memory_profiler
- cProfile是python内置包,它主要用来统计函数调用以及每个函数所占的cpu时间。
- line_profiler可以帮你一行一行分析函数性能。
- memory_profiler帮你一行一行分析函数内存消耗。
1. cProfile
首先你需要运行分析器,生成结果;然后你需要对结果进行各种格式化分析
- 第一步你可以通过cProfile.run()方法或者cProfile.runctx()方法或者cProfile.Profile类来实现
- 第二步是通过pstats.Stats类实现
一个简单的示例见Instant User’s Manual
2. line_profiler
Once installed you’ll have access to a new module called “line_profiler
” as well as an executable script kernprof.py.
使用这个工具有两种方法:
(1)使用命令行
- first modify your source code by decorating the function you want to measure with the
@profile
decorator.The kernprof.py script automatically injects it into your script’s runtime during execution. Once you’ve gotten your code setup with the
@profile
decorator, use kernprof.py to run your script.$ kernprof -l -v fib.py
The
-l
option tellskernprof
to inject the@profile
decorator into your script’s builtins, and-v
tellskernprof
to display timing information once you’re script finishes.如果没有-v
选项,分析结果将会被写入script_to_profile.py.lprof
文件。
(2)使用API(推荐)
第一种方法是通过命令行分析,其实你还可以通过API来分析,line_profiler
提供了和cProfile
类似的API,
Code Example:
import line_profiler
import sys
def test():
print 'haha'
prof = line_profiler.LineProfiler(test)
prof.enable() # 开始性能分析
test()
prof.disable() # 停止性能分析
prof.print_stats(sys.stdout)
Output
haha
Timer unit: 5.70172e-07 s
Total time: 4.50436e-05 s
File: C:/Users/wangjiang/PycharmProjects/Test/sk_test.py
Function: test at line 5
Line # Hits Time Per Hit % Time Line Contents
--------------------------------------------------------------
5 def test():
6 1 79 79.0 100.0 print('haha')
(Time一列1代表1微秒)
这种方法你不需要使用装饰器,也不需要显式使用kernprof(实际上依然是使用这个工具实现的,只不过封装了你看不到)
3. memory_profiler
(1) 安装psutil,memory_profiler
pip install psutil
pip install memory_profiler
(2) 代码里
首先添加
from memory_profiler import profile
然后在某个函数上添加装饰器@profile
(3) 命令行执行:
python -m memory_profiler example.py
Ref
Python性能分析与优化
A guide to analyzing Python performance
Github-rkern/line_profiler
https://pypi.python.org/pypi/memory_profiler