import time # 函数装饰器 def runtime(fun1): def inner(*args, **kwargs): """inner doc """ start_time = time.time() f = fun1(*args, **kwargs) time.sleep(1) end_time = time.time() interval = end_time - start_time print("function %s 运行时间:%s " % (fun1.__name__, interval))
return f return inner @runtime def fun_a(a): """fun_a : hello + a""" print("hello"+a) # print(fun_a.__name__) # print(fun_a.__doc__) fun_a('a') #类装饰器 class Runtime(object): def __init__(self, delay=1): self.delay = delay def __call__(self, fun): """Runtime doc""" def inner(*args, **kwargs): """inner doc""" start_time = time.time() f = fun(*args,**kwargs) time.sleep(self.delay-1) end_time = time.time() interval = end_time - start_time print("function %s 运行时间:%.4f " % (fun.__name__, interval)) return f return inner @Runtime(2) def fun_a(a): """fun_a : hello + a""" print("hello"+a) print(fun_a.__name__) print(fun_a.__doc__) fun_a('a')