%timeit和变量的重新分配

时间:2019-09-30 08:22:08

标签: python ipython

令人惊讶的ipython magic %timeit错误:

In[1]: a = 2

In[2]: %timeit a = 2 * a

Traceback (most recent call last):
  File "...\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-97-6f70919654d1>", line 1, in <module>
    get_ipython().run_line_magic('timeit', 'a = 2 * a')
  File "...\site-packages\IPython\core\interactiveshell.py", line 2314, in run_line_magic
    result = fn(*args, **kwargs)
  File "<...\site-packages\decorator.py:decorator-gen-61>", line 2, in timeit
  File "...\site-packages\IPython\core\magic.py", line 187, in <lambda>
    call = lambda f, *a, **k: f(*a, **k)
  File "...\site-packages\IPython\core\magics\execution.py", line 1158, in timeit
    time_number = timer.timeit(number)
  File "...\site-packages\IPython\core\magics\execution.py", line 169, in timeit
    timing = self.inner(it, self.timer)
  File "<magic-timeit>", line 1, in inner
UnboundLocalError: local variable 'a' referenced before assignment

因此%timeit不喜欢自我重新分配。为什么?无论如何要克服这个问题?

3 个答案:

答案 0 :(得分:2)

与基础timeit模块一样,定时语句被集成到执行定时的生成函数中。分配给a会使函数具有一个a局部变量,从而隐藏全局变量。就像你做完一样的问题

a = 2

def f():
    a = 2 * a

f()

尽管生成的函数具有更多的代码。

答案 1 :(得分:1)

您可以使用一些%%魔法来避免赋值错误:

%%timeit
a = 2
a = a*2

答案 2 :(得分:1)

具有初始化功能的单元格timeit:

In [142]: %%timeit a=2 
     ...: a = 2*a 
     ...:  
     ...:                                                                       
2.68 µs ± 66.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)