gpt4 book ai didi

python - 如何多次运行一个函数

转载 作者:太空宇宙 更新时间:2023-11-03 12:17:24 32 4
gpt4 key购买 nike

我必须在 1000 次运行中找出函数运行时间的平均值。我应该使用哪个代码让它运行 1000 次然后求出它们的平均值?我的功能是:

import time

t0 = time.clock()

def binary_search(my_list, x):

left=0
right=len(my_list)-1
while left<=right:
mid = (left+right)//2
if my_list[mid]==x:
return True
elif my_list[mid] < x: #go to right half
left = mid+1
else: #go to left half
right = mid-1
return False #if we got here the search failed
t1 = time.clock()

print("Running time: ", t1-t0, "sec")

最佳答案

你应该使用 timeit这个模块:

>>> timeit.timeit('test()', setup='from __main__ import test')
0.86482962529626661

获取平均结果:

>>> timeit.timeit('test()', setup='from __main__ import test', number=1000)/1000
8.4928631724778825e-07

关于python - 如何多次运行一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20525503/

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