性能分析器cProfile、line_profiler、memory_profiler

来源:互联网 发布:华腾网络机柜 编辑:程序博客网 时间:2024/05/17 07:20

性能分析器主要有两个模块:cProfileline_profilermemory_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)使用命令行

  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.
  2. 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 tells kernprof to inject the @profile decorator into your script’s builtins, and -v tells kernprof 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

0 0
原创粉丝点击