timeit在python管理中不工作。py壳

时间:2021-01-07 23:19:18

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

我必须花时间在django项目(即python管理)中运行查询。py壳

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管理中不起作用。py壳

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

从进口a1到a1有一些问题。

1 个解决方案

#1


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():

我遇到了同样的问题,也没有找到真正的解决办法。对于一些代码行(如您示例中的代码),可以直接将它们放在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?

然而,尽管它不能帮助解释为什么在时间上的导入不能在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

#1


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():

我遇到了同样的问题,也没有找到真正的解决办法。对于一些代码行(如您示例中的代码),可以直接将它们放在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?

然而,尽管它不能帮助解释为什么在时间上的导入不能在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