timing in python with %timeit %%timeit how to keep/retain values for later use

无人久伴 提交于 2019-12-10 18:38:47

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/48769703/timing-in-python-with-timeit-timeit-how-to-keep-retain-values-for-later-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!