python中的装饰器用于修饰函数,以增强函数的行为:记录函数执行时间,建立和撤销环境,记录日志等。
装饰器可以在不修改函数内部代码的前提下实现以上增强行为。
同样的代码段,封装在函数内,运行速度快,那是因为局部变量比全局变量效率高,所以尽量减少全局变量的使用量。
# 计算素数 t1 = time.time() lst_com = [] for i in range(2, 10001): is_com = 0 if i ==2 or i == 3: lst_com.append(i) if i % 2 ==0 or i % 3 == 0: continue for j in range(6, int(math.sqrt(i))+2, 6): if i % (j-1) == 0 or i % (j+1) == 0: is_com = 1 if is_com == 1: continue lst_com.append(i) # print(lst_com) t2 = time.time() print(f'取出素数{len(lst_com)}个,耗时{t2-t1}秒。') def prime_number(str_num, end_num): t1 = time.time() lst_com = [] for i in range(str_num, end_num): is_com = 0 if i ==2 or i == 3: lst_com.append(i) if i % 2 ==0 or i % 3 == 0: continue for j in range(6, int(math.sqrt(i))+2, 6): if i % (j-1) == 0 or i % (j+1) == 0: is_com = 1 if is_com == 1: continue lst_com.append(i) # print(lst_com) t2 = time.time() print(f'取出素数{len(lst_com)}个,耗时{t2-t1}秒。') if __name__ == '__main__': prime_number(2, 1000001, times=100) 输出结果: 取出素数1229个,耗时0.0109710693359375秒。 取出素数1229个,耗时0.00698089599609375秒。
import math import time def run_time(func): """ 外层为装饰器函数,参数为被装饰的函数 """ def wrapper(*args,**kwargs): """ 内层为功能增强函数,可以接收被装饰函数的参数,其中,*args:接收位置参数,**kwargs:接收关键字参数 """ start = time.time() result = func(*args,**kwargs) end = time.time() print(f'*args:{args}') print(f'**kwargs:{kwargs}') print(f'运行时间(s):{end - start}') return result return wrapper @run_time def prime_number(str_num, end_num, times): lst_com = [] for i in range(str_num, end_num): is_com = 0 if i ==2 or i == 3: lst_com.append(i) if i % 2 ==0 or i % 3 == 0: continue for j in range(6, int(math.sqrt(i))+2, 6): if i % (j-1) == 0 or i % (j+1) == 0: is_com = 1 if is_com == 1: continue lst_com.append(i) # print(lst_com) print(f'取出素数{len(lst_com)}个') if __name__ == '__main__': prime_number(2, 1000001, times=100) 输出结果: 取出素数1229个 args:(2, 10001) kwargs:{'times': 100} 运行时间(s):0.007979631423950195
import math import time def run_time(doc): """ 外层为装饰器函数,接收装饰器函数的参数 """ def logger(func): """ 中间层参数为被装饰的函数 """ print(f'装饰器函数的参数doc为:{doc}') def wrapper(*args,**kwargs): """ 内层为功能增强函数,可以接收被装饰函数的参数,其中,*args:接收位置参数,**kwargs:接收关键字参数 """ start = time.time() result = func(*args,**kwargs) end = time.time() print(f'*args:{args}') print(f'**kwargs:{kwargs}') print(f'运行时间(s):{end - start}') return result return wrapper return logger @run_time(123) def prime_number(str_num, end_num, times): lst_com = [] for i in range(str_num, end_num): is_com = 0 if i ==2 or i == 3: lst_com.append(i) if i % 2 ==0 or i % 3 == 0: continue for j in range(6, int(math.sqrt(i))+2, 6): if i % (j-1) == 0 or i % (j+1) == 0: is_com = 1 if is_com == 1: continue lst_com.append(i) # print(lst_com) print(f'取出素数{len(lst_com)}个') if __name__ == '__main__': prime_number(2, 1000001, times=100) 输出结果: 装饰器函数的参数doc为:123 取出素数1229个 *args:(2, 10001) **kwargs:{'times': 100} 运行时间(s):0.006983757019042969