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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
RadRuss
  • 484
  • 2
  • 6
  • 16
  • Related: https://github.com/ipython/ipython/issues/5767. – jonrsharpe Feb 25 '18 at 10:33
  • 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! – RadRuss Feb 25 '18 at 10:56
  • A recent question like this [timing in python with %timeit %%timeit how to keep/retain values for later use](https://stackoverflow.com/questions/48769703/timing-in-python-with-timeit-timeit-how-to-keep-retain-values-for-later-use) – hpaulj Feb 25 '18 at 17:19
  • Related: https://stackoverflow.com/questions/32565829/simple-way-to-measure-cell-execution-time-in-ipython-notebook – mic Apr 25 '20 at 03:29
  • 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. – mic Apr 25 '20 at 03:30

1 Answers1

3

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.

user2314737
  • 27,088
  • 20
  • 102
  • 114