1. 程式人生 > >簡單裝飾器

簡單裝飾器

程式碼實現:

import time

def timer(func): #timer(test1) func=test1
    def deco():
        start_time=time.time()
        func()
        end_time=time.time()
        print("the fun run time is %s"%(end_time-start_time))
    return deco

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

test1()

執行結果:

C:\Users\jelena.zhao\AppData\Local\Programs\Python\Python36\python3.exe E:/pythonscripts/study/test1/dir01/decorator.py
in the test1
the fun run time is 3.010200023651123
in the test1
the fun run time is 2.9952001571655273

Process finished with exit code 0