Python question about time spent

daydreamer picture daydreamer · Jun 29, 2010 · Viewed 7.3k times · Source

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

Answer

Justin L. picture Justin L. · Jun 29, 2010

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()