timeit 在 python manage.py shell 中不起作用

Viv*_*ble 3 python django django-manage.py

我必须找到在 django 项目中运行查询所花费的时间,即python manage.py shell

代码:

>>> 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: >>>
Run Code Online (Sandbox Code Playgroud)

这在 python manage.py shell 中不起作用

但这是工作文件,我在 py 文件中编写代码并运行命令行。

有问题from __main__ import a1 as a1

sga*_*ble 5

timeit在不同的上下文中执行,因此它无法访问您导入/定义的符号。

为此,您可以:

使用setup其构造函数的参数。

timeit.timeit("a1()", setup="from __main__ import a1 as a1")
Run Code Online (Sandbox Code Playgroud)

使用globals其构造函数的参数(Python >= 3.5)来传递全局命名空间。

timeit.timeit("a1()", globals=globals())
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅文档。