性能分析器cProfile、line_profiler、memory_profiler
来源:互联网 发布:华腾网络机柜 编辑:程序博客网 时间:2024/05/17 07:20
性能分析器主要有两个模块: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_profilerimport sysdef test(): print 'haha'prof = line_profiler.LineProfiler(test)prof.enable() # 开始性能分析test()prof.disable() # 停止性能分析prof.print_stats(sys.stdout)
Output
hahaTimer unit: 5.70172e-07 sTotal time: 4.50436e-05 sFile: C:/Users/wangjiang/PycharmProjects/Test/sk_test.pyFunction: test at line 5Line # Hits Time Per Hit % Time Line Contents============================================================== 5 def test(): 6 1 79 79.0 100.0 print('haha')
(Time一列1代表1微秒)
这种方法你不需要使用装饰器,也不需要显式使用kernprof(实际上依然是使用这个工具实现的,只不过封装了你看不到)
More Info 见这里
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
More Info 见这里
Ref
Python性能分析与优化
A guide to analyzing Python performance
Github-rkern/line_profiler
https://pypi.python.org/pypi/memory_profiler
- 性能分析器cProfile、line_profiler、memory_profiler
- Python的7种性能测试工具:timeit、profile、cProfile、line_profiler、memory_profiler、PyCharm图形化性能测试工具、objgraph
- 使用memory_profiler 与 cProfile ,line_profiler 优化Python程序运行时间和内存消耗实例
- Python脚本性能剖析-cprofile
- python的性能分析工具line_profiler
- python 性能调试工具(line_profiler)使用
- 应用python的性能测量工具cProfile
- 应用python的性能测量工具cProfile
- 使用cProfile分析Python程序性能
- python性能分析工具:cProfile使用
- Python中cProfile性能分析工具的使用
- 代码性能分析器 dotTrace
- VTune性能分析器简介
- VTune性能分析器简介
- VTune性能分析器简介
- VTune性能分析器简介
- Intel VTune 性能分析器
- VTune性能分析器简介
- UIButton 的一些设置
- Windows下编译安装64位Nginx
- Linux建立和删除用户
- Android与JS的交互简单实现
- gitbook入门详解
- 性能分析器cProfile、line_profiler、memory_profiler
- Android 自定义View (四) 视频音量调控
- request和response总结
- javascript里面的 && 和 || 的妙用
- 和为S的两个数
- Android 快速开发系列 打造万能的ListView GridView 适配器
- jquery实现遮罩层
- 这个感恩节,滴滴用讲故事的方式温暖你我
- 各种域对象保存购物信息