I am trying to measure the execution time of different parts of my code, a few lines each. I am doing this with %%timeit, however after I execute a cell, I find that the values calculated for variables in the cell are not kept in memory for next cells, as in the following example.
Why does this happen? Is there a way to retain the values so I can use them in the rest of the program?
In [1]: %%timeit
...: dog='dog'
100000000 loops, best of 3: 16.2 ns per loop
In [2]: print (dog)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
in ()
----> 1 print (dog)
NameError: name 'dog' is not defined
This sounds like an apparently trivial question to me (or what I would expect as default behavior), but I wasn't able to find any information online, so I hope someone can help.
解决方案
Just ran this:
%%timeit
dog='dog'
for i in range(100000000):
i += 1
print(i)
print(dog)
in a jupyter notebook online and it gave:
100000000
dog
100000000
dog
100000000
dog
100000000
dog
100000000
dog
100000000
dog
100000000
dog
100000000
dog
6.6 s ± 123 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
try it.