1π
β
I have encountered the same problem and have found no real solution. What works for a few lines of code like the one in your example, is putting them directly in the setup
parameter of timeit():
>>> setup = 'd={"a":1, "b":2}\ndef a1():\n for i in d:\n a = i, d[i]\n'
>>> print "Time 1:", timeit.timeit('a1()', setup)
Time 1: 0.337239027023
Yet, while it does not help explain why the import in timeit
doesnβt work in the django shell, why not implement your own timing function?
>>> import time
>>> def time_function(fnc, number=10**6):
>>> start = time.time()
>>> for i in xrange(number):
>>> fnc()
>>> return time.time() - start
>>> print "Time 1:", time_function(a1)
Time 1: 0.3310558795928955
π€user2390182
5π
timeit
is executed in a different context, so it does not have access to symbols you import/define.
To do so you can either:
Use the setup
parameter of its constructor.
timeit.timeit("a1()", setup="from __main__ import a1 as a1")
Use the globals
parameter (Python >= 3.5) of its constructor to pass the global namespace.
timeit.timeit("a1()", globals=globals())
See the doc for more details.
π€sgable
Source:stackexchange.com