如何比较执行相同任务的两个函数的效率(哪个更快)

问题描述 投票:0回答:4

我有两个函数,需要比较它们以提高效率(更快)。最好的方法是什么?

python performance function time compare
4个回答
1
投票

最简单的方法是您可以使用时间库中的时间函数。

import time

start = time.time()
my_function() # This is the task which I have done
end = time.time()
print(end - start)

1
投票

使用类似的东西怎么样?

import time

start = time.time()
print("hello")
end = time.time()
print(end - start)

基于此处提供的解决方案:解决方案


0
投票

取决于你的功能有多强烈。如果是简单的事情并且您想比较某些功能,您应该运行它们几次

import time

t0 = time.time()
for i in range(1,10000):
    yourfunction()
t1 = time.time()

for i in range(1,10000):
    yourotherfunction()
t2 = time.time()

print(t1-t0, t2-t1)

0
投票

您需要 timeit 函数。它将多次运行您的测试用例并返回计时。您经常会看到人们在比较不同方法之间的性能时引用 timeit 的结果。

您可以在此处

找到相关文档
© www.soinside.com 2019 - 2024. All rights reserved.