defword_count():passdefmain():from time import time
t = time()
word_count()print('时间消耗:%.2f秒'%(time()- t))if __name__ =='__main__':
main()
遍历列表时间测试
deff1(ls):for i in ls:print(i)deff2(ls):for i inrange(len(ls)):print(ls.pop())if __name__ =='__main__':from time import time
ls =list(range(99999))
t0 = time()
f1(ls)
t1 = time()
f2(ls)
t2 = time()print(t1 - t0)print(t2 - t1)
测试结果
| function | time(秒) |
| - | - |
| f1 | 0.41 |
| f2 | 0.42 |
wraps装饰器
from time import time
from functools import wraps
deffn_timer(fn):
@wraps(fn)deffunction_timer(*args,**kwargs):
t = time()
result = fn(*args,**kwargs)print('【%s】运行时间:%.4f秒'%(fn.__name__, time()- t))return result
return function_timer
@fn_timer
deff():pass