首页 > 技术文章 > 实现多函数计时功能--及装饰器实现

dbslinux 2019-07-16 08:22 原文

现在有一个新的需求,希望可以记录下函数的执行时间,于是在代码中添加日志代码:

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)
 
 
那利用装饰器实现:
import time
def show_time(f):
def inner():
start_time=time.time()
f()
end=time.time()
print('spend %s' %(end-start_time))
return inner
@show_time
def bar():
print('hello bar')
time.sleep(3)
bar()
@show_time
def foo():
print('hello foo')
time.sleep(5)
foo()
这样就即没有更改原代码,也没修改调用方式了
那什么是装饰器?
:装饰器也是一特殊函数,装饰就是添加新的功能--为你之前的函数foo(),bar()添加某个功能--如计时功能,所以show-time函数就叫一装饰器!!

推荐阅读