计算代码运行时长

  1. # 计算代码执行的时间
  2. import time
  3. start = time.time()
  4. x = 0
  5. for i in range(1, 100000000):
  6. x += 1
  7. print(x)
  8. end = time.time()
  9. print('代码运行了{}s'.format(end - start))

>

  1. 99999999
  2. 代码运行了6.123429298400879s

那么每次运行代码前后都需要这样编写,是非常麻烦的,这个时候就引入装饰器

装饰器的基本使用

```python

-- coding: utf-8 --

@Author: afei

计算代码执行的时间

import time

start = time.time()

def use_time(fn): def inner(x): start = time.time() s = fn(x) end = time.time() print(‘代码运行了{}’.format(end - start)) return s return inner

@use_time def fun1(n): x = 0 for i in range(1,n): x += i return x fun1(12345667)

  1. >>>
  2. ```python
  3. 代码运行了0.4541590213775635

args和*kwargs

  1. # -*- coding: utf-8 -*-
  2. # @Author: afei
  3. # 计算代码执行的时间
  4. import time
  5. # start = time.time()
  6. def use_time(fn):
  7. def inner(x,*args,**kwargs):
  8. start = time.time()
  9. s = fn(x)
  10. end = time.time()
  11. print('代码运行了{}'.format(end - start))
  12. return s
  13. return inner
  14. @use_time
  15. def fun1(n):
  16. x = 0
  17. for i in range(1,n):
  18. x += i
  19. return x
  20. fun1(12345667,'hello',b=1234556)

>

  1. 代码运行了0.5189573764801025