python装饰器小例子

import time

def timer(func): #timer(test1) func=test1
def deco(*args,**kwargs):
start_time=time.time()
func(*args,**kwargs)
stop_time=time.time()
print("the func run time %s" %(stop_time-start_time))
return deco

@timer #test1=timer(test1)
def test1():
time.sleep(3)
print("in the test1")

@timer
def test2(name,age):
time.sleep(2)
print("in the test2" ,name,age)


test1()
test2("joan",5)


输出结果:

in the test1
the func run time 3.0043931007385254
in the test2 joan 5
the func run time 2.0034029483795166

posted @ 2017-07-02 21:13  joangaga  阅读(339)  评论(0编辑  收藏  举报