我正在尝试计算泡沫和插入排序。排序适用于它们两个,但它输出需要15秒,这显然是不正确的。有任何建议如何解决这个问题?
# insertion sort
x = [7, 2, 3, 5, 9, 1]
def insertion(list):
for index in range(1,len(list)):
value = list[index]
i = index - 1
while i>=0 and (value < list[i]):
list[i+1] = list[i] # shift number in slot i right to slot i+1
list[i] = value # shift value left into slot i
i = i - 1
# bubble sort
y = [7, 2, 3, 5, 9, 1]
def bubble(unsorted_list):
length = len(unsorted_list) - 1
sorted = False
while not sorted:
sorted = True
for i in range(length):
if unsorted_list[i] > unsorted_list[i+1]:
sorted = False
unsorted_list[i], unsorted_list[i+1] = unsorted_list[i+1], unsorted_list[i]
def test():
bubble(y)
insertion(x)
if __name__ == '__main__':
import timeit
print(timeit.timeit("test()", setup="from __main__ import test"))
答案 0 :(得分:5)
timeit.timeit (stmt ='pass',setup ='pass',timer =, 号码= 1000000)
使用给定语句创建Timer实例, 设置代码和计时器功能,并使用数字运行其timeit()方法 执行。
所以你的代码运行了1,000,000次。将返回值除以10**6
,您就可以了。
答案 1 :(得分:0)
profile也是您可以考虑的选项。
答案 2 :(得分:-1)
尝试此操作,捕获当前时间,执行该功能,然后从当前时间中减去先前捕获的时间。
# insertion sort
x = [7, 2, 3, 5, 9, 1]
def insertion(list):
for index in range(1,len(list)):
value = list[index]
i = index - 1
while i>=0 and (value < list[i]):
list[i+1] = list[i] # shift number in slot i right to slot i+1
list[i] = value # shift value left into slot i
i = i - 1
# bubble sort
y = [7, 2, 3, 5, 9, 1]
def bubble(unsorted_list):
length = len(unsorted_list) - 1
sorted = False
while not sorted:
sorted = True
for i in range(length):
if unsorted_list[i] > unsorted_list[i+1]:
sorted = False
unsorted_list[i], unsorted_list[i+1] = unsorted_list[i+1], unsorted_list[i]
def test():
start = time.clock()
bubble(y)
elapsed = (time.clock() - start)
print "Time taken for bubble = ", elapsed
start = time.clock()
insertion(x)
elapsed = (time.clock() - start)
print "Time taken for Insertion = ", elapsed
if __name__ == '__main__':
import time
test()