3

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?

deceze
  • 510,633
  • 85
  • 743
  • 889
MarcoQ
  • 33
  • 1
  • 3

2 Answers2

3

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.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
  • Ok, I see that it's a different namespace, but I'm not sure I understand why, what's the benefit of it? The point of me writing c=a+b was to calculate c. Why did it have to take it to a different namespace so that I don't get the result? – MarcoQ Mar 07 '16 at 11:48
  • You'd have to read the `timeit` library code to get that level of detail - I can tell you what is happening, but not why. – holdenweb Mar 07 '16 at 11:55
  • `timeit` may run your code many times, even thousands. In your example I get `10000000 loops, best of 3: 55.6 ns per loop`. Typically I run the expression once to check the value, and then use `timeit` to test performance. – hpaulj Mar 08 '16 at 02:11
2

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.

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889