源代码
# author:莲师
import time,logging
def timmer(func):
def wrapper(*args,**kwargs):
print('programe strat running...')
start = time.time()
try:
result = func(*args,**kwargs)
end = time.time()
runtime = end - start
print('running %s s'%runtime)
return result
except:logging.error('programe running err!')
finally: print('programe end running!\n')
return wrapper
使用方法
另存为 timmmer.py ,使用时引用这个文件内的timmer类
比如:
import time,sys,logging
from timmer import timmer
@timmer
def cal(n):
s = 0
for i in range(1,n+1):s += i
return s
def main ():
try:print(cal(int(sys.argv[1])))
except:log.error('please input int type!')
if __name__ == '__main__':
log = logging.Logger(__name__)
main()
在需要查看运行时间的函数前加上这个timmer语法糖
@timmer
在shell内输入命令
python cal.py 100000
会有:
programe strat running...
running 0.006545066833496094 s
programe end running!
5000050000
OK! 获取到了运行时间!装饰器还在一定程度上实现了程序本身的容错功能,就不再演示了。