stu*_*stu 3 python python-2.7 python-3.x
我必须在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")
Run Code Online (Sandbox Code Playgroud)
你应该使用这个timeit
模块:
>>> timeit.timeit('test()', setup='from __main__ import test')
0.86482962529626661
Run Code Online (Sandbox Code Playgroud)
获得平均结果:
>>> timeit.timeit('test()', setup='from __main__ import test', number=1000)/1000
8.4928631724778825e-07
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3165 次 |
最近记录: |