Magic function timeit

3.4k Views Asked by At

I'm using the magic %%timeit function to get the time it takes to execute some code. The thing that bothers me is that when I run %%timeit, I don't get the results. For instace:

a=5
b=3

%%timeit
c = a + b

Now if I want to use c in the next cell, I get that c hasn't been defined.

print(c)
>>>NameError: name 'c' is not defined

Could you help me understand why this happens, why doesn't c get stored when the magic %%timeit function is used in that particular cell?

2

There are 2 best solutions below

3
holdenweb On BEST ANSWER

When you time code with %%timeit, the code you provide is executed within a separate namespace, and so its effects are not visible to your environment.

0
deceze On

cell mode:

%%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code code code...

In cell mode, the statement in the first line is used as setup code (executed but not timed) and the body of the cell is timed. The cell body has access to any variables created in the setup code.

https://ipython.org/ipython-doc/3/interactive/magics.html#magic-timeit

You're executing in cell mode, and the line is just setup code; which means it's not actually timed and its results are only accessible to the cell code following it.