Q:

How to time bubble and insertion sorting?

I'm trying to time the bubble and the insertion sorting. The sorting works fine for both of them, but it outputs that it takes 15 seconds, which is clearly incorrect. Any suggestions how to fix this?
# 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"))

A:

From the timeit documentation:

timeit.timeit(stmt='pass', setup='pass', timer=,
  number=1000000)
Create a Timer instance with the given statement,
  setup code and timer function and run its timeit() method with number
  executions.

So your code is running 1,000,000 times. Divide the return value by 10**6 and you'll be on your way.

A:

try this, you capture the current time, execute the function and then subtract the previous captured time from the current time.
# 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() 

