LoginSignup
4
1

More than 5 years have passed since last update.

%timeや%%time等の結果をオブジェクト(変数)に格納したい

Posted at

IPython(Jupyter)のline magicやcell magicの出力、その他諸々の出力を標準出力ではなく、オブジェクト(変数)に格納して後から加工したいということがたまにあるかもしれません。(例: 実行した関数の戻り値じゃなくて出力が欲しい)

あまり褒められたやり方ではないかもしれませんが、sys.stdoutの出力先を一時的にStringIOへ飛ばしてしまう方法で実装してみます。

  • 準備
try:
    from io import StringIO  # Python3
except:
    from cStringIO import StringIO  # Python2
import sys

old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
  • %%timeの出力をハンドリング
%%time
for i in range(1000000):
    i ** 2
  • 後始末(必ずやるように!)
sys.stdout = old_stdout
  • 結果を取得
clock_times = mystdout.getvalue()
print(clock_times)
CPU times: user 467 ms, sys: 0 ns, total: 467 ms
Wall time: 469 ms
4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1