在python中测试函数计算速度最准确的方法是什么



见过time.perfcounter()timeit.timeit()time.time()等几种方法。但是,哪种方法最准确?

您可以使用装饰器来计算函数的执行时间。请参阅以下示例。

# 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)

您可以将此应用于任何函数。

相关内容

最新更新