python 装饰器本身就是一个函数,它的作用是装饰一个其他的函数,但是不改变原有的程序功能,还能增添新的功能,调用函数时用@timer 。
编写 test_timer.py 如下
# coding:utf-8
""" 装饰器函数 运行计时器 """
import sys
from functools import reduce
import time
# 函数可以嵌套其它函数中定义
def timer(function):
""" 装饰器函数 timer, 其中 funcation 为要装饰的函数 """
def wrapper(args, *kv):
start = time.perf_counter()
function(args, *kv)
end = time.perf_counter()
spend_time = end-start
print(f"spend time: {spend_time} s")
return wrapper
@timer
def factorial(n:int):
""" 计算阶乘 n! """
fact = reduce(lambda x,y: x*y, range(1,n+1))
print(f"{n}! = {fact}")
# main()
if len(sys.argv) ==2:
n = int(sys.argv[1])
else:
print('usage: python test_timer.py n ')
sys.exit(1)
factorial(n)
运行 python test_timer.py 30
30! = 265252859812191058636308480000000
spend time: 0.00013499999999999623 s

347

被折叠的 条评论
为什么被折叠?



