如何存储%% timeit cell magic的结果? [英] How to store the result from %%timeit cell magic?

查看:545
本文介绍了如何存储%% timeit cell magic的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何存储来自单元魔法的结果 - %% timeit ?我读过:

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


  1. 你能捕获ipython魔术方法的输出吗?

  2. 捕获IPython魔术函数的结果

  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?

推荐答案

你可以使用 _ 变量(存储最后的结果)在 %% timeit -o 单元格之后并将其分配给某个可重用变量:

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>






我不认为这是一个错误,因为细胞模式命令必须是该单元格中的第一个命令,因此您不能在该命令前放置任何内容(甚至不是 res = ... )。

但是你还需要 -o ,否则 _ 变量包含

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

这篇关于如何存储%% timeit cell magic的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆