import math
import time
import random
def sequential_search(key,sorted_list):
for element in sorted_list:
if element==key:
return True
else :
return False
def binary_search(key,sorted_list):
l=0
r=len(sorted_list)-1
while l<=r:
m=int(math.floor((l+r)/2))
if key==sorted_list[m]:
return m
elif key<sorted_list[m]:
r=m-1
else:
l=m+1
def ternary_search(key,sorted_list):
length = len(sorted_list)
left = 0
right = length
index = 0
x = True
while x and left <= right:
#focal = (high + low) //3
if left == right:
#check similarity between values and key
return left
elif right - left > 0:
index1 = ((right+2*(left))//3)
index2 = ((2*(right)+left)//3)
if sorted_list[index1] == key:
return index1
elif sorted_list[index2] == key:
return index2
else:
if key<sorted_list[index1]:
right = index1 - 1
elif key > sorted_list[index1] and key <sorted_list[index2]:
right = index2 - 1
left = index1 - 1
elif key > sorted_list[index2]:
left = index2+1
return index
def interpolation_search(key, sorted_list):
low = 0
high = len(sorted_list) - 1
while sorted_list[low] <= key and sorted_list[high] >= key:
mid = low + ((key - sorted_list[low]) * (high - low)) \
/(sorted_list[high] - sorted_list[low])
# out of range is possible
if sorted_list[mid] < key:
low = mid + 1
elif sorted_list[mid] < key:
high = mid - 1
else:
return mid
if sorted_list[low] == key:
return low
return None
def run_experiment():
sorted_list=random.sample(range(1000000), 1000)
sorted_list.sort()
key=random.randint(0,1000001)
key=1000001
time_ss=time.time()
sequential_search(key,sorted_list)
time_ss_end=time.time()
print time_ss_end-time_ss
time_bs=time.time()
binary_search(key,sorted_list)
print time.time()-time_bs
time_ts=time.time()
ternary_search(key,sorted_list)
print time.time()-time_ts
time_is=time.time()
interpolation_search(key,sorted_list)
print time.time()-time_is
if __name__ == '__main__':
run_experiment()
raw_input("Stop")
我是Python新手。我想測量這些算法的時間,所以我使用「時間」方法。但輸出如下:python中的時間分析
>>>
0.0
0.0
0.0
0.0
>>>
有時第一次測量會發生變化。我怎樣才能改變這些輸出?我應該更改我的代碼以進行時間分析嗎?
可能重複的[在Python中的函數的準確時間](http://stackoverflow.com/questions/889900/accurate-timing-of-功能合蟒) –