最近因为项目要求,需要对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