现在有一个新的需求,希望可以记录下函数的执行时间,于是在代码中添加日志代码:
import time
def foo(): start_time=time.time() print('hello foo') time.sleep(3) end_time=time.time() print('spend %s'%(end_time-start_time))foo()bar()、bar2()也有类似的需求计时,怎么做?再在bar函数里调用时间函数?这样就造成大量雷同的代码,为了减少重复写代码,我们可以这样做,重新定义一个函数:专门设定时间show_time:
import time def show_time(func): start_time=time.time() func() end_time=time.time() print('spend %s'%(end_time-start_time))def foo(): print('hello foo') time.sleep(3)show_time(foo)