5

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)
<ipython-input-16-c61686862278> in <module>()
----> 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.

Vincenzooo
  • 2,013
  • 1
  • 19
  • 33
  • Statements run in a timeit block are executed many times (1000s). Where possible you want those repetitions to run independently, separate from values in the main namespace or values created in previous runs. And you (or at least I) don't want those values clogging or modifying my main namespace. Setting global values and timing code should be separate tasks. – hpaulj Feb 13 '18 at 17:43
  • 2
    I agree, but if I have a complex mathematical calculation made of many steps and I want to time each step I need to retain values. Also the fact that the statements are run many times is not relevant, I am not using random numbers, input and output are always the same and also steps are computational intensive, they never gets executed more than once. At the moment the only option I have is repeat each step twice (timing it first time and not timing the second) that is not a very clean approach. Or maybe I could put them in different functions and profile them, that I don't like either. – Vincenzooo Feb 13 '18 at 18:30
  • 2
    I usually run test blocks twice. Once to check the values, and again for timing. But feel free to study the code for `%timeit` to see how it localizes the namespace. See https://stackoverflow.com/questions/48269712/ipython-timeit-local-variable-a-referenced-before-assignment for a variation on this problem (initializing a local variable). – hpaulj Feb 13 '18 at 18:40

0 Answers0