Yosmart Hariandja
Yosmart Hariandja

Reputation: 3

Measure code timing in python. What did I wrong?

import time
s = time.time()
def insertionSort(alist):
    for index in range(1, len(alist)):

        currentvalue = alist[index]
        position = index

        while position > 0 and alist[position - 1] > currentvalue:
            alist[position] = alist[position - 1]
            position = position - 1

        alist[position] = currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print (time.time() - s) # Result 0.0

I look up for time module, but is hard to me as newbie to read it. I already searching an answer what comes up it's measure the start of code and end of a code. And the result is 0.0. Please help me with this.

Upvotes: 0

Views: 201

Answers (1)

Alex Fung
Alex Fung

Reputation: 2006

There is nothing wrong with how you use time.time.

The reason that 0.0 was printed is the code ran so quickly that the timer did not change at all.

To illustrate my point, I have looped your code for 1000 times.

import time
s = time.time()
def insertionSort(alist):
    for index in range(1, len(alist)):

        currentvalue = alist[index]
        position = index

        while position > 0 and alist[position - 1] > currentvalue:
            alist[position] = alist[position - 1]
            position = position - 1

        alist[position] = currentvalue
for x in xrange(1000):
    insertionSort([54,26,93,17,77,31,44,55,20])
e = time.time()
print (e - s) 

Output:

0.00600004196167

There is a bulti-in library called timeit which is useful for this situation if you are interested in code performance.

import timeit
t = timeit.Timer("insertionSort([54,26,93,17,77,31,44,55,20])", "from __main__ import insertionSort")
time = t.timeit(1000)
print(time)

Output:

0.00587430725292

Upvotes: 1

Related Questions