%%timeit not returning defined variable
Asked Answered
T

1

13

I'm trying to use IPython magic command %%timeit and I run into some problems. The chunk that I'm trying to time is not returning a variable I define in it.

Specifically, let's say I want to measure how long does it take to set variable var to 30.

%%timeit
var = 5 * 6

Running this chunk, I get something like 16.8 ns ± 0.303 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each). When I later try to call var, I get NameError: name 'var' is not defined.

I found this question, however, I'm not sure what to take from it. Also, it is from 2014 so I think there could have been some changes.

Is there a way how to 'keep' variable defined in a chunk with %%timeit so that it can be later called?

I'm using Python 3.6, Anaconda 4.4.10.

Tadio answered 25/2, 2018 at 10:29 Comment(5)
Related: github.com/ipython/ipython/issues/5767.Zolner
After reading through the issue, I assume that there is no simple solution and I should simply abandon the idea of doing this. Thanks for the link!Tadio
A recent question like this timing in python with %timeit %%timeit how to keep/retain values for later usePadre
Related: #32566329Lineolate
If you're okay with only running it once, you can use %%time instead of %%timeit. %%time has been changed within the past year or so to remember variables.Lineolate
E
4

Just use the %%time cell magic instead (or the %time line magic)

%time var = 5 * 6
# CPU times: user 2 µs, sys: 0 ns, total: 2 µs
# Wall time: 3.81 µs

var
# Out: 30

I guess the reason why variables are not remembered by %timeit is that it's a series of experiments--when experimenting one should always assume that something might go wrong, so it's not clear what the valid variable instantiation should be.

To see what kind of repeated runs %%timeit performs, check also my other answer.

Envious answered 10/4, 2022 at 13:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.