Search code examples
djangodjango-extensionsdjango-commands

django shell_plus timeit call_command?


I've written a django command and want to see it's timing so inside django shell_plus I do this:

import timeit
from django.core.management import call_command

timeit.timeit("""call_command('prova')""", number=3 )

The command should run 3 times and output its running time.

If run directly 'call_command' it works, if called inside timeit it throw this error:

/usr/lib/python3.5/timeit.py in timeit(self, number)
    176         gc.disable()
    177         try:
--> 178             timing = self.inner(it, self.timer)
    179         finally:
    180             if gcold:

/usr/lib/python3.5/timeit.py in inner(_it, _timer)

NameError: name 'call_command' is not defined

Solution

  • timeit always runs within a new execution context, it doesn't have access to anything you previously imported. You need to pass a separate parameter with setup code:

    timeit.timeit("call_command('prova')", number=3, setup='from django.core.management import call_command' )
    

    See the timeit docs.