RadRuss
RadRuss

Reputation: 524

%%timeit not returning defined variable

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.

Upvotes: 13

Views: 2947

Answers (1)

user2314737
user2314737

Reputation: 29417

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.

Upvotes: 4

Related Questions