Aquí está un ejemplo de cómo compartimentar la rutina de temporización, sin globales que llaman
def foo(a, b):
'''Do something to `a` and `b`'''
return a + b
def time_foo():
'''Create timer object simply without using global variables'''
import timeit
_foo = foo
a = 1
b = 2
# Get `Timer` oject, alternatively just get time with `timeit.timeit()`
t = timeit.Timer('_foo(a, b)', globals=locals())
return t
Usted podría incluso generalice esto si quiere usar la misma función timeit
para sincronizar otras funciones. He aquí un ejemplo con su ejemplo main()
rutina:
def foo1(a, b):
'''Add `a` and `b`'''
return a + b
def foo2(a, b):
'''More math on `a` and `b`'''
return (a**2 * b)**2
def time_foo(func, **kwargs):
'''Create timer object simply without using global variables'''
import timeit
return timeit.timeit('func(**kwargs)', globals=locals())
def run():
'''Modify inputs to foo and see affect on execution time'''
a = 1
b = 2
for i in range(10):
# Update `a` and `b`
a += 1
b += 2
# Pass args to foo as **kwargs dict
print('foo1 time: ', time_foo(foo1, **{'a':a, 'b':b}))
print('foo2 time: ', time_foo(foo2, **{'a':a, 'b':b}))
return None
Bueno, antes que nada, la sangría aquí es confusa. Parece que 'foo' se está definiendo en un ámbito diferente que' t' ... – senderle
hi. arreglé la sangría se ve mejor ahora? :] Gracias. – CppLearner
timeit está bien para frases sencillas, pero para cualquier otra cosa mejor, compruebe este método http://stackoverflow.com/questions/5478351/python-time-measure-function – vincent