python - How do you use timeit to time how long it takes a function to run? -


trying figure out how long takes piece of code run:

import timeit t  def fib_recursive(n):      if n==0:         return 0     elif n == 1:         return 1     else:         return fib_recursive(n-1) + fib_recursive(n-2) print fib_recursive(29) print t.timer("fib_recursive(29)") 

output following:

514229 timeit.timer instance @ 0xda28c0

to expand on thefourtheye's comment (which correct), want isolate steps necessary define function setup parameter timeit. given setup, following:

import timeit t  def fib_recursive(n):     if n==0:         return 0     elif n == 1:         return 1     else:         return fib_recursive(n-1) + fib_recursive(n-2)  setup = 'from __main__ import fib_recursive' t.timeit('fib_recursive(29)', setup=setup) 

i'll assume you're aware of various techniques improve algorithm , choosing measure speed establish baseline only. can experiment number keyword parameter timeit control number of repetitions.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -