需求:有一个做加法计算的函数,要统计执行这个加法函数代码运行了多久
import timedef add(a, b):time.sleep(1)return a + bst = time.time()
add(100, 200)
et = time.time()
print("该函数运行时间为:", et - st)
学了闭包+装饰器后:
import time# 通过函数实现装饰器
def count_time(func):def wrapper(*args, **kwargs):st = time.time()res = func(*args, **kwargs)et = time.time()print("该函数运行时间为:", et - st)return resreturn wrapper@count_time
def add(a, b):time.sleep(1)return a + bprint(add(200, 300))
又学了魔术方法后:
import time# 通过类实现装饰器
class CountTime:def __init__(self, func):self.func = funcdef __call__(self, *args, **kwargs):st = time.time()res = self.func(*args, **kwargs)et = time.time()print("该函数运行时间为:", et - st)return res@CountTime # add = CountTime(add)
def add(a, b):time.sleep(1)return a + bprint(add(200, 300))
需求升级:
装饰器接收一个int类型的参数n,可以用来装饰任何函数,如果函数运行时间大于n,则
打印“请耐心等待,马上回来”和统计函数的运行时间
# 通过函数实现装饰器
import timedef count_time_1(n):def count_time(func):def wrapper(*args, **kwargs):st = time.time()res = func(*args, **kwargs)et = time.time()print("该函数运行时间为:", et - st)if et - st > n:print("请耐心等待,马上回来")return resreturn wrapperreturn count_time@count_time_1(2) # add = count_time(2)(add)
def add(a, b):time.sleep(2)return a + bprint(add(200, 300))
# 通过类实现装饰器
class CountTime:def __init__(self, n):self.n = ndef __call__(self, func):def wrapper(*args, **kwargs):st = time.time()res = func(*args, **kwargs)et = time.time()print("该函数运行时间为:", et - st)if et - st > self.n:print(f"运行时间超过{self.n}s,请耐心等待,马上回来")return resreturn wrapper@CountTime(1) # add = CountTime(1)(add)
def add(a, b):time.sleep(1)return a + bprint(add(100, 200))