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을 처음 사용합니다. 이러한 알고리즘의 시간을 측정하여 "시간"방법을 사용하려고합니다. 출력은 다음과 같습니다.파이썬의 시간 분석
>>>
0.0
0.0
0.0
0.0
>>>
가끔 첫 번째 측정이 변경됩니다. 출력물을 어떻게 바꿀 수 있습니까? 시간 분석을 위해 코드를 변경해야합니까?
가능한 정확한 [Python 함수의 정확한 타이밍] (http://stackoverflow.com/questions/889900/accurate-timing-of- 파이썬 기능) –