添加Python包装器测试函数运行速度,见代码:
#coding:utf-8
#timethis.py
#测试函数运行时间
import time
from functools import wraps
def timethis(func):
'''
Decorator that reports the execution time.
'''
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, end-start)
return result
return wrapper
#eof
@timethis
def test1(count=100):
nums=[]
for i in range(count):
nums.append(i)
nums.reverse()
@timethis
def test2(count=100):
nums=[]
for i in range(count):
nums.insert(0,i)
@timethis
def countdown(n):
'''
Counts down
'''
while n > 0:
n -= 1
if __name__=="__main__":
count=100000
countdown(count)
countdown(count*100)
test2(count)
test1(count*250)
''' 运行结果 list.insert(0,i)运行速度几乎漫250倍
>>>
=============== RESTART: D:\Python\Python37\py\yzq\timethis.py ===============
countdown 0.013000726699829102
countdown 0.6510372161865234
test2 2.9441685676574707
test1 3.0301735401153564
>>>
'''