gpt4 book ai didi

python - 如何在python中测量算法的运行时间

转载 作者:IT老高 更新时间:2023-10-28 22:19:42 25 4
gpt4 key购买 nike

Possible Duplicates:
Accurate timing of functions in python
accurately measure time python function takes

我如何测量和比较我用 python 编写的算法的运行时间。如果可以的话,还请给我一个不错的算法站点/论坛,例如 stackoverflow。

最佳答案

对于小型算法,您可以使用模块 timeit来自 python 文档:

def test():
"Stupid test function"
L = []
for i in range(100):
L.append(i)

if __name__=='__main__':
from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit()

不太准确但仍然有效,您可以像这样使用模块时间:

from time import time
t0 = time()
call_mifuntion_vers_1()
t1 = time()
call_mifunction_vers_2()
t2 = time()

print 'function vers1 takes %f' %(t1-t0)
print 'function vers2 takes %f' %(t2-t1)

关于python - 如何在python中测量算法的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2662140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com