python测试代码性能,python代码性能测试

最近因为项目要求,需要对python代码进行性能测试,简单学习几种常见解决方法:

实例代码test.py:

# -*- coding: utf-8 -*-

# @Time : 2020/3/30 12:04 上午

# @Author : renwoxing

# @File : test.py

# @Software: PyCharm

def compareString(A, B):

A_len = len(A)

B_len = len(B)

if A == B or 0 == len(A) or 0 == len(B):

return True

if A_len > B_len:

sub = A_len - B_len

for i in range(sub):

if A[i:B_len+1] == B:

return True

return False

else:

sub = B_len - A_len

for i in range(sub):

if B[i:A_len+1] == A:

return True

return False

if __name__ == '__main__':

A = "ABCD"

B = "BC"

compareString(A, B)

1 )测试代码整体消耗时间,使用unix 的time函数

# time python3 test.py

python3 test.py 0.02s user 0.02s system 72% cpu 0.051 total

2)使用cProfile 模块测试代码细节

# python3 -m cProfile test.py

8 function calls in 0.000 seconds

Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)

1 0.000 0.000 0.000 0.000 test.py:8()

1 0.000 0.000 0.000 0.000 test.py:8(compareString)

1 0.000 0.000 0.000 0.000 {built-in method builtins.exec}

4 0.000 0.000 0.000 0.000 {built-in method builtins.len}

1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}

3) 使用装饰器

# -*- coding: utf-8 -*-

# @Time : 2020/4/1 11:21 下午

# @Author : renwoxing

# @File : performance_test.py

# @Software: PyCharm

from functools import wraps

import time

def timethis(func):

@wraps(func)

def wrapper(*args, **kwargs):

start = time.process_time()

r = func(*args, **kwargs)

end = time.process_time()

print('{}.{} : {}'.format(func.__module__, func.__name__, end - start))

return r

return wrapper

@timethis

def countdown(n):

while n > 0:

n -= 1

if __name__ == '__main__':

countdown(1000)

4)测试较小的代码片段

from timeit import timeit

timeit('math.sqrt(2)', 'import math')

0.09831449999999897

timeit('sqrt(2)', 'from math import sqrt')

0.06704933299999993

5)测试某个代码块运行时间,可以定义一个上下文管理器

from contextlib import contextmanager

@contextmanager

def timeblock(label):

start = time.perf_counter()

try:

yield

finally:

end = time.perf_counter()

print('{} : {}'.format(label, end - start))

>>> with timeblock('counting'):

... n = 10000000

... while n > 0:

... n -= 1

...

counting : 1.5551159381866455

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值