计算代码运行时长
# 计算代码执行的时间
import time
start = time.time()
x = 0
for i in range(1, 100000000):
x += 1
print(x)
end = time.time()
print('代码运行了{}s'.format(end - start))
>
99999999
代码运行了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)
>>>
```python
代码运行了0.4541590213775635
args和*kwargs
# -*- coding: utf-8 -*-
# @Author: afei
# 计算代码执行的时间
import time
# start = time.time()
def use_time(fn):
def inner(x,*args,**kwargs):
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,'hello',b=1234556)
>
代码运行了0.5189573764801025