Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to measure running time of algorithms in python [duplicate]

Possible Duplicates:
Accurate timing of functions in python
accurately measure time python function takes

How can i mesure and compare the running times of my algorithms written in python .Also point me to a nice algorithms site/forum like stackoverflow if you can.

like image 919
Bunny Rabbit Avatar asked Apr 18 '10 12:04

Bunny Rabbit


2 Answers

For small algorithms you can use the module timeit from python documentation:

def test():
    "Stupid test function"
    L = []
    for i in range(100):
        L.append(i)

if __name__=='__main__':
    from timeit import Timer
    t = Timer("test()", "from __main__ import test")
    print t.timeit()

Less accurately but still valid you can use module time like this:

from time import time
t0 = time()
call_mifuntion_vers_1()
t1 = time()
call_mifunction_vers_2()
t2 = time()

print 'function vers1 takes %f' %(t1-t0)
print 'function vers2 takes %f' %(t2-t1)
like image 80
joaquin Avatar answered Nov 07 '22 13:11

joaquin


The module timeit is useful for this and is included in the standard Python distribution.

Example:

import timeit
timeit.Timer('for i in xrange(10): oct(i)').timeit()
like image 25
Mark Byers Avatar answered Nov 07 '22 14:11

Mark Byers