目录:

1.timeit

  1.1 在命令后调用timeit

  1.2 在代码中使用

  1.3 创建计时器实例,通过autorange获得循环次数

  1.4 Wall时间和CPU时间

2.profile和cProfile

  2.1 使用cProfile

  2.2 将cProfile封装成装饰器 或 上下文  

  2.3 line_profiler 逐行分析代码耗时

  2.4 memory profiler 逐行分析代码占用内存


1.timeit  python标准库自带

其算法如下:

  1. 将代码循环之行多次(参数名number),以便有足够长的统计时间。
  2. 将步骤 1 循环执行多次(参数名repeat),获取足够多的有统计采样。
  3. 从步骤 2 的结果选取耗时最短的采样,计算单次平均值。

1.1命令行执行

(djProj_py3) appledeMacBook-Air-7:tests apple$ python -m timeit -r 3 -s "import time" "time.sleep(1)"
10 loops, best of 3: 1 sec per loop

1.2 在代码中调用

import timeit
# 执行 算法第一步
timeit.timeit("time.sleep(1)", setup="import time", number=10)
>>>
[10.027022889000364]
# 执行 算法第二步
timeit.repeat("time.sleep(1)", setup="import time", number=10, repeat=3)
>>>
[10.030386196999643, 10.036546275000546, 10.020536892000564]

1.3创建计时器实例,可以使用autorange方法探测合适的循环次数

In [4]: import timeit

In [5]: t = timeit.Timer("time.sleep(0.002)", "import time")

In [6]: t.autorange()
Out[6]: (100, 0.2527182700000594)

1.4 默认使用高精度计时器统计Wall时间,也可以改为统计CPU时间。

参数名 timer:   Wall -- time.perf_counter

        CPU -- time.process_time

timeit.timeit("time.sleep(1)", "import time", number=10, timer=time.process_time)  # 指定统计CPU时间

2.profile和cProfile

2.1 cProfile以C实现,额外开销小。profile以python实现,相关开销大会导致测量误差较大,适合用来编写扩展分析器。

测试代码:

import time

def a():
n = 0
for i in range(1000):
n += 1
time.sleep(1)
return n def b():
n = 0
for i in range(3):
n += a()
print(n)
return n if __name__ == "__main__":
b()

开始测试:

 ncalls:被调用总次数 
tottime: 总执行时间(不包括调用的子函数)
percall: tottime/ncalls
cumtime: 执行总时间(包括调用的子函数)
percall: cumtime / ncalls
(djProj_py3) appledeMacBook-Air-7:tests apple$ python -m cProfile -s cumtime test_a.py
3000
11 function calls in 3.010 seconds Ordered by: cumulative time
  # 次数 不包括子函数 平均 包括子函数 平均
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 3.010 3.010 {built-in method builtins.exec}
1 0.000 0.000 3.010 3.010 test_a.py:1(<module>)
1 0.000 0.000 3.010 3.010 test_a.py:12(b)
3 0.000 0.000 3.010 1.003 test_a.py:4(a)
3 3.009 1.003 3.009 1.003 {built-in method time.sleep}
1 0.000 0.000 0.000 0.000 {built-in method builtins.print}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}

2.2 一般将cProfile封装成装饰器 或 上下文

2.2.1装饰器

def profile(sortby="cumtime", limit=1, timer=time.perf_counter):
def decorator(func):
@functools.wraps(func)
def warp(*args, **kwargs):
p = cProfile.Profile(timer)
p.enable() # 类似启动的功能
try:
return func(*args, **kwargs)
finally:
p.disable() # 类似停止
s = pstats.Stats(p).sort_stats(sortby)
s.print_stats(limit) # 限制输出几行
return warp
return decorator def a():
n = 0
for i in range(1000):
n += 1
time.sleep(1)
return n @profile()
def b():
n = 0
for i in range(3):
n += a()
return n if __name__ == "__main__":
b() >>>
(djProj_py3) appledeMacBook-Air-7:tests apple$ python test_a.py
8 function calls in 3.013 seconds Ordered by: cumulative time
List reduced from 4 to 1 due to restriction <1> ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 3.013 3.013 test_a.py:28(b)

2.2.2 上下文

import cProfile, pstats, contextlib, time

@contextlib.contextmanager
def profile1(sortby='cumtime', limit=10, timer=time.perf_counter):
p = cProfile.Profile(timer)
p.enable()
try:
yield
finally:
p.disable()
s = pstats.Stats(p).sort_stats(sortby)
s.print_stats(limit) def a():
n = 0
for i in range(1000):
n += 1
time.sleep(1)
return n @profile1()
def b():
n = 0
for i in range(3):
n += a()
return n if __name__ == "__main__":
b() >>>
(djProj_py3) appledeMacBook-Air-7:tests apple$ python test_a.py
11 function calls in 3.013 seconds Ordered by: cumulative time ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 3.013 3.013 test_a.py:39(b)
3 0.001 0.000 3.013 1.004 test_a.py:31(a)
3 3.012 1.004 3.012 1.004 {built-in method time.sleep}
1 0.000 0.000 0.000 0.000 /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py:85(__exit__)
1 0.000 0.000 0.000 0.000 {built-in method builtins.next}
1 0.000 0.000 0.000 0.000 test_a.py:20(profile1)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}

  2.3 line_profiler

 通过上面的cProfile可以分析得到引发性能的函数,line_profiler可以对该函数代码逐行分析

  首先 pip install line_profiler

  

@profile  # 此装饰器,安装了line_profiler,才只能通过命令 kernprof -l -v test_a.py 分析每行性能
def test():
for i in range(3):
a = [1] * (10 ** 6)
b = [2] * (2 * 10 ** 7)
del b
return a if __name__ == "__main__":
test() >>>

(djProj_py3) appledeMacBook-Air-7:tests apple$ kernprof -l -v test_a.py

Wrote profile results to test_a.py.lprof    # -l 储存进文件   -v 显示
Timer unit: 1e-06 s


Total time: 0.147605 s
File: test_a.py
Function: test at line 40

Line # Hits Time Per Hit % Time Line Contents
==============================================================
40 @profile
41 def test():
42 4 19.0 4.8 0.0 for i in range(3):
43 3 15401.0 5133.7 10.4 a = [1] * (10 ** 6)
44 1 73001.0 73001.0 49.5 b = [2] * (2 * 10 ** 7)
45 1 59182.0 59182.0 40.1 del b
46 1 2.0 2.0 0.0 return a


2.4 memory profiler

逐行分析代码内存占用

首先 pip install memory_profiler

@profile
def test():
for i in range(3):
a = [1] * (10 ** 6)
b = [2] * (2 * 10 ** 7)
del b
return a >>>
(djProj_py3) appledeMacBook-Air-7:tests apple$ python -m memory_profiler test_a.py
Filename: test_a.py Line # Mem usage Increment Line Contents
================================================
40 31.000 MiB 31.000 MiB @profile
41 def test():
42 46.266 MiB 0.000 MiB for i in range(3):
43 46.266 MiB 15.266 MiB a = [1] * (10 ** 6)
44 198.855 MiB 152.590 MiB b = [2] * (2 * 10 ** 7)
45 46.266 MiB -152.590 MiB del b
46 46.266 MiB 0.000 MiB return a

python-性能测试的更多相关文章

  1. python 性能测试

            python中使用的性能测试模块是memory_profiler , 我们使用它里面的profile这个装饰器即可测试出我们的代码的内存使用情况了.   如果没有安装 memory_p ...

  2. 好用的python性能测试神器–Locust

    原文链接:https://mp.weixin.qq.com/s/9PxSPuHmucSLi_welq6uNQ 现在性能测试工具太多,根据业务不同使用,比如说我们熟悉的loadrunner.jmeter ...

  3. Python性能测试

    python -m profile xxx.py > log.txt 打开log.txt查看,搜索你所关心的方法调用耗费的时间. profile的统计结果分为ncalls.tottime.per ...

  4. python性能测试大致计划

      hi guy: 如果注意到创建时间,那就对了.这份文章,是我学习Python一个月以后动手写的.   写下这份计划以后,只完成了第一步,其中磕磕绊绊编写代码的过程,很大一部分时间是完全用txt写的 ...

  5. python性能测试脚本-乾颐堂

    废话不多说,直接上代码. import httplib import urllib import time import json     class Transaction(object):     ...

  6. python性能测试值timeit的使用示例

    from timeit import Timer def t1(): li = [] for i in range(10000): li.append(i) def t2(): li = [] for ...

  7. python 各种开源库

    测试开发 来源:https://www.jianshu.com/p/ea6f7fb69501 Web UI测试自动化 splinter - web UI测试工具,基于selnium封装. 链接 sel ...

  8. python 三方面库整理

    测试开发 Web UI测试自动化 splinter - web UI测试工具,基于selnium封装. selenium - web UI自动化测试. –推荐 mechanize- Python中有状 ...

  9. python测试框架&&数据生成&&工具最全资源汇总

    xUnit frameworks 单元测试框架frameworks 框架unittest - python自带的单元测试库,开箱即用unittest2 - 加强版的单元测试框架,适用于Python 2 ...

  10. Python代码样例列表

    扫描左上角二维码,关注公众账号 数字货币量化投资,回复“1279”,获取以下600个Python经典例子源码 ├─algorithm│       Python用户推荐系统曼哈顿算法实现.py│    ...

随机推荐

  1. 基于OLSR的路由协议实现Ad-Hoc组网

    一.软件包的安装 1. olsrd软件包的安装 libpthread_0.9.33.2-1_ar71xx.ipk olsrd_0.6.6.2-4_ar71xx.ipk 2. luci的安装 olsrd ...

  2. JAVA常量与变量

    顺着箭头的转换为自动转换逆这箭头的转换为强制转换. 常量 关键字FINAL 命名为大写 标识符 1要以字母数字下划线和¥组成 2首字母不能为数字 3不能是JAVA的关键字和 保留字 4数据类型分为基本 ...

  3. 微信开发-业务域名、JS接口安全域名、网页授权域名

    在微信公众平台上可配置这些域名. 1.业务域名:在微信浏览器中点击文本框,会弹出下面的提示,很不爽,通过配置业务域名可以将该提示去掉 2.JS接口安全域名:分享到朋友圈(js-sdk)时用上,此接口要 ...

  4. Myeclipse 2017安装

    一.下载 Myeclipse官网下载地址:http://www.myeclipsecn.com/download/ 二.安装 安装详细步骤省略,仅仅是一路下一步即可,博主默认安装到了C盘,注意:安装完 ...

  5. Azure ARM (15) 根据现有VHD文件,创建ARM VM

    <Windows Azure Platform 系列文章目录> 在很多时候,我们需要根据现有VHD文件,创建ARM VM.在这里笔者简单介绍一下相关的Azure PowerShell 这里 ...

  6. mongodb 慕课网

    ------------------------------------------------mongodb简述------------------------------------------- ...

  7. Could not write to output file 'c:\Windows\Microsoft.NET ASP.NET Files\xx' -- 'Access is denied

    网上有IIS7的解决方法,是给"C:\Windows\Temp"文件夹加上添加用户IIS_IUSRS的完全控制权限. 但我这个老机器是IIS6的,没有IIS_IUSERS用户,只能 ...

  8. DEVC怎么建工程

    1.DEVC建工程 1.1 新建项目 打开文件,选择新建-->项目-->ConsoleApplication(控制台程序),输入项目名,选择保存路径.(单独建一个文件夹存放) 项目建成功后 ...

  9. ubuntu更新提示/boot空间不足

    1. 查看当前使用的内核版本 uname -a 2.在终端下察看已经安装的旧的内核: ctrl+alt+t——>进入终端——>输入命令: dpkg --get-selections|gre ...

  10. 关于oracle的sqlplus显示不完全的修改方法

    这样的显示看起来很痛苦 需要换行的时候没有进行换行,不需要换行的时候却进行了换行 参考的博客地址 https://blog.csdn.net/pan_tian/article/details/8059 ...