How to store the result from %%timeit cell magic?

时光毁灭记忆、已成空白 提交于 2019-11-30 02:49:46

问题


I can't figure out how to store the result from cell magic - %%timeit? I've read:

  1. Can you capture the output of ipython's magic methods?
  2. Capture the result of an IPython magic function

and in this questions answers only about line magic. In line mode (%) this works:

In[1]: res = %timeit -o np.linalg.inv(A)

But in cell mode (%%) it does not:

In[2]: res = %%timeit -o 
       A = np.mat('1 2 3; 7 4 9; 5 6 1')
       np.linalg.inv(A)

It simply executes the cell, no magic. Is it a bug or I'm doing something wrong?


回答1:


You can use the _ variable (stores the last result) after the %%timeit -o cell and assign it to some reusable variable:

In[2]: %%timeit -o 
       A = np.mat('1 2 3; 7 4 9; 5 6 1')
       np.linalg.inv(A)
Out[2]: blabla
        <TimeitResult : 1 loop, best of 3: 588 µs per loop>

In[3]: res = _

In[4]: res
Out[4]: <TimeitResult : 1 loop, best of 3: 588 µs per loop>

I don't think it's a bug because cell mode commands must be the first command in that cell so you can't put anything (not even res = ...) in front of that command.

However you still need the -o because otherwise the _ variable contains None.



来源:https://stackoverflow.com/questions/41351041/how-to-store-the-result-from-timeit-cell-magic

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