Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python question about time spent

I would like to know that how much time a particular function has spent during the duration of the program which involves recursion, what is the best way of doing it?

Thank you

like image 813
daydreamer Avatar asked Jun 29 '10 21:06

daydreamer


2 Answers

The best way would be to run some benchmark tests (to test individual functions) or Profiling (to test an entire application/program). Python comes with built-in Profilers.

Alternatively, you could go back to the very basics by simply setting a start time at the beginning of the program, and, at the end of the program, subtracting the current time from the start time. This is basically very simple Benchmarking.

Here is an implementation from the an answer from the linked question:

import time
start = time.time()
do_long_code()
print "it took", time.time() - start, "seconds."

Python has something for benchmarking included in its standard library, as well.

From the example give on the page:

def test():
    "Time me"
    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()
like image 62
Justin L. Avatar answered Oct 22 '22 11:10

Justin L.


Use the profiler!

python -m cProfile -o prof yourscript.py
runsnake prof

runsnake is a nice tool for looking at the profiling output. You can of course use other tools.

More on the Profiler here: http://docs.python.org/library/profile.html

like image 39
Will Avatar answered Oct 22 '22 10:10

Will