[英]timeit is not working in the python manage.py shell
I have to find time taken to run query in django project ie python manage.py shell
我必须找到时间在 django 项目中运行查询,即
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这在 python manage.py shell 中不起作用
But this is working file I write code in py file and run my command line.但这是工作文件,我在 py 文件中编写代码并运行我的命令行。
There is something wrong in from __main__ import a1 as a1
from __main__ import a1 as a1
timeit
is executed in a different context, so it does not have access to symbols you import/define. timeit
在不同的上下文中执行,因此它无法访问您导入/定义的符号。
To do so you can either:为此,您可以:
Use the setup
parameter of its constructor.使用其构造函数的
setup
参数。
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.使用其构造函数的
globals
参数(Python >= 3.5)来传递全局命名空间。
timeit.timeit("a1()", globals=globals())
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():适用于您示例中的几行代码的方法是将它们直接放在 timeit() 的
setup
参数中:
>>> 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?然而,虽然它无助于解释为什么
timeit
中的导入在 django shell 中不起作用,但为什么不实现自己的计时功能呢?
>>> 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.