import time import random import searching def make_list(n): '''Return a random list of n elements.''' res = range(n) random.shuffle(res) return res def time_search(f, L, n): '''Return how many seconds it takes to run searching function f on a list with n random ints and a random search key.''' t1 = time.time() ans = f(L, n) t2 = time.time() return t2 - t1 def time_index(L,n): '''Return how many seconds it takes to run list.index on a list with n random ints, and a random search key.''' t1 = time.time() ans = L.index(n) t2 = time.time() return t2 - t1 def make_sorted_list(n): '''Return a random sorted list of n elements. There may be duplicates. Values in the list will be between 0 and 100 times the len of list.''' res = [] for i in range(n): res[i] = random.randint(0, n*100) sort(res) return res def time_binary_search(n): '''Return how many seconds it takes to run binary search on a sorted list with n random ints and a random search key.''' L = range(n) t1 = time.time() ans = searching.binary_search(L, random.randint(0, n)) t2 = time.time() return t2 - t1 if __name__ == "__main__": for size in [4000, 8000, 32000, 1024000]: L = make_list(size) n = random.randint(0, size) print "==", size, "==" s = time_search(searching.search, L,n) print "search:", s ss = time_search(searching.sentinel_search, L,n) print "sentinel search:", ss bs = time_binary_search(size) print "binary search:",bs ti = time_index(L,n) print "list.index:", ti print "simple search is:" print " %f times slower than sentinel search" % (s/ss) print " %f times slower than list.index" % (s/ti) print "comparison with binary search is not fair, since", print "binary search knows its list is sorted"