Algunas veces querrás tomar nota del tiempo promedio que toma ejecutar alguna función. Seguramente ya sabes que puedes usar el módulo timeit, pero seguramente te encontrarás unos cuantos inconvenientes...


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

import timeit
timeit.timeit("test()")


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-60e1cbc15514> in <module>()
      6 
      7 import timeit
----> 8 timeit.timeit("test()")

/usr/lib/python2.7/timeit.pyc in timeit(stmt, setup, timer, number)
    228            number=default_number):
    229     """Convenience function to create Timer object and call timeit method."""
--> 230     return Timer(stmt, setup, timer).timeit(number)
    231 
    232 def repeat(stmt="pass", setup="pass", timer=default_timer,

/usr/lib/python2.7/timeit.pyc in timeit(self, number)
    193         gc.disable()
    194         try:
--> 195             timing = self.inner(it, self.timer)
    196         finally:
    197             if gcold:

/usr/lib/python2.7/timeit.pyc in inner(_it, _timer)

NameError: global name 'test' is not defined

El nombre global 'test' no está definido. Y sí, tiene razón. De hecho la documentación de timeit dice que debes utilizar el parámetro setup para ello. Aunque la verdad prefiero algo más sencillo y directo (en este tipo de casos):


In [2]:
timeit.timeit(lambda: test())


Out[2]:
9.818758010864258

Y sí, también funciona con parámetros


In [3]:
import calendar
import random
def daysinyear(year):
    """ Returns how many days has the year """
    return 366 if calendar.isleap(year) else 365

year = random.randint(1900, 2014)

timeit.timeit(lambda: daysinyear(year))


Out[3]:
0.46839189529418945