Skip to content Skip to sidebar Skip to footer

%timeit And Re-assignment Of Variable

Surprising ipython magic %timeit error: In[1]: a = 2 In[2]: %timeit a = 2 * a Traceback (most recent call last): File '...\site-packages\IPython\core\interactiveshell.py', line

Solution 1:

As with the underlying timeit module, the timed statement is integrated into a generated function that performs the timing. The assignment to a causes the function to have an a local variable, hiding the global. It's the same issue as if you had done

a = 2def f():
    a = 2 * a

f()

although the generated function has more code than that.

Solution 2:

You could use some %% magic instead to avoid the assignment error:

%%timeit
a = 2
a = a*2

Solution 3:

The cell timeit with initialization works:

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

Post a Comment for "%timeit And Re-assignment Of Variable"