python中装饰器的运行问题
import timeimport functools
def clock(func):
@functools.wraps(func)
def clocked(*args, **kwargs):
t0 = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - t0
name = func.__name__
arg_lst = []
if args:
arg_lst.append(','.join(repr(arg) for arg in args))
if kwargs:
pairs = ['%s=%r' % (k, w) for k, w in sorted(kwargs.items())]
arg_lst.append(','.join(pairs))
arg_str = ','.join(arg_lst)
print('[%0.8fs] %s(%s)-> %r' % (elapsed, name, arg_str, result))
return result
return clocked
@clock
def snooze(seconds):
time.sleep(seconds)
@clock
def factorial(n):
return 1 if n < 2 else n*factorial(n-1)
if __name__ == '__main__':
print('*' * 40, 'Calling snooze(.123)')
snooze(.123)
print('*' * 40, 'Calling factorial(6)')
print('6! =', factorial(6))
这个程序运用了clock装饰器,输出函数运行所花的时间。
输出结果如下:
**************************************** Calling snooze(.123)
snooze(0.123)-> None
**************************************** Calling factorial(6)
factorial(1)-> 1
factorial(2)-> 2
factorial(3)-> 6
factorial(4)-> 24
factorial(5)-> 120
factorial(6)-> 720
6! = 720
为什么后边调用factoria()函数时,运行时间都是0呢?
我也尝试了修改保留小数点后的位数,可是结果还是一样的。
调用snooze()函数时,运行时间却没问题。 **************************************** Calling snooze(.123)
snooze(0.123)-> None
**************************************** Calling factorial(6)
factorial(1)-> 1
factorial(2)-> 2
factorial(3)-> 6
factorial(4)-> 24
factorial(5)-> 120
factorial(6)-> 720
6! = 720
没问题啊 kogawananari 发表于 2021-6-3 07:36
没问题啊
那就奇怪了,我运行出来的结果都是0秒。
不过我修改了 t0 = time.time()这个语句
t0 = time.perf_counter()
下边的elapsed也都修改了,执行后就好了,
不知道是什么原因?
页:
[1]