|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- import time
- import 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)
[0.12480021s] snooze(0.123)-> None
**************************************** Calling factorial(6)
[0.00000000s] factorial(1)-> 1
[0.00000000s] factorial(2)-> 2
[0.00000000s] factorial(3)-> 6
[0.00000000s] factorial(4)-> 24
[0.00000000s] factorial(5)-> 120
[0.00000000s] factorial(6)-> 720
6! = 720
为什么后边调用factoria()函数时,运行时间都是0呢?
我也尝试了修改保留小数点后的位数,可是结果还是一样的。
调用snooze()函数时,运行时间却没问题。 |
|