实用python小工具--函数运行时间装饰器

装饰器定义如下:

1
2
3
4
5
6
7
8
import time
def CalculateTime(a_func):
def wrapTheFunction():
start = time.time()
a_func()
cost = time.time() - start
print(f"Function \"{a_func.__name__}\" cost : {cost} second(s).")
return wrapTheFunction

测试部分

1
2
3
4
5
6
7
8
9
10
11
@CalculateTime
def func():
s = 0
for i in range(10 ** 7):
s += 1
print(s)


if __name__ == '__main__':
func()

结果

1
2
10000000
Function "func" cost : 1.7449958324432373 second(s).