Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magic function timeit

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?

like image 870
MarcoQ Avatar asked Apr 11 '26 23:04

MarcoQ


2 Answers

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.

like image 159
holdenweb Avatar answered Apr 14 '26 11:04

holdenweb


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.

like image 35
deceze Avatar answered Apr 14 '26 13:04

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!