热线电话:13121318867

登录
2019-02-13 阅读量: 662
python如何输出函数执行时间

使用装饰器轻松找出函数的执行时间

# importing libraries

import time

import math

# decorator to calculate duration

# taken by any function.

def calculate_time(func):

# added arguments inside the inner1,

# if function takes any arguments,

# can be added like this.

def inner1(*args, **kwargs):

# storing time before function execution

begin = time.time()

func(*args, **kwargs)

# storing time after function execution

end = time.time()

print("Total time taken in : ", func.__name__, end - begin)

return inner1

# this can be added to any function present,

# in this case to calculate a factorial

@calculate_time

def factorial(num):

# sleep 2 seconds because it takes very less time

# so that you can see the actual difference

time.sleep(2)

print(math.factorial(num))

# calling the function.

factorial(10)

输出;

3628800
Total time taken in : factorial 2.0061802864074707
7.1474
2
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子