Search code examples
pythondjangodjango-manage.py

timeit is not working in the python manage.py shell


I have to find time taken to run query in django project i.e. python manage.py shell

code:

>>> import timeit
>>> d = {"a":1, "b":2}
>>> def a1():
...     for i in d:
...         a = i, d[i]
... 
>>> a1()


>>> print "Time 1:", timeit.timeit('a1()', 'from __main__ import a1 as a1')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib64/python2.6/timeit.py", line 227, in timeit
    return Timer(stmt, setup, timer).timeit(number)
  File "/usr/lib64/python2.6/timeit.py", line 193, in timeit
    timing = self.inner(it, self.timer)
  File "<timeit-src>", line 3, in inner
ImportError: cannot import name a1
Time 1: >>>

This is not working in python manage.py shell

But this is working file I write code in py file and run my command line.

There is something wrong in from __main__ import a1 as a1


Solution

  • 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