Python笔记(32)装饰器之案例解析

    技术2026-04-18  1

    #!/user/bin/env python # -*- coding:utf-8 -*- # author:berlin # 需求如下: # 有两个函数,都有自己的逻辑,各自实现功能,在实现功能的过程需要消耗时间, # 从而写一个装饰器来统计这两个函数的运行时间。 import time # 定义一个嵌套函数 def timeer(func): #相当于timeer(test1)和timeer(test2) func=test1和func=test2 def deco(): start_time=time.time() func() stop_time=time.time() print('the func run time is %s' %(start_time-stop_time)) return deco @timeer #相当于test1=timeer(test1) def test1(): time.sleep(3) print('in the test1') @timeer #相当于test2=timeer(test2) def test2(): time.sleep(3) print('in the test2') # 最后再调用两个函数 test1() test2()
    Processed: 0.009, SQL: 9