11
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

jupyter notebookAdvent Calendar 2019

Day 4

%time, %timeitの結果を加工する

Last updated at Posted at 2019-12-04

Jupyter/IPythonで%time%timeitで実行時間を計測できるのはよく知られていると思いますが、これを加工したり可視化したいと思ったことはないでしょうか?

%%captureを使うと、標準出力をPythonのオブジェクトとして扱えます。
実際にやってみましょう。

%%capture result
%timeit 2 ** 100

%%captureの引数がオブジェクト名となります、ほかのオプションについてはヘルプを参照してください。

  %capture [--no-stderr] [--no-stdout] [--no-display] [output]

run the cell, capturing stdout, stderr, and IPython's rich display() calls.

positional arguments:
  output        The name of the variable in which to store output. This is a utils.io.CapturedIO
                object with stdout/err attributes for the text of the captured output.
                CapturedOutput also has a show() method for displaying the output, and __call__ as
                well, so you can use that to quickly display the output. If unspecified, captured
                output is discarded.

stdout属性を参照すると、標準出力が文字列に格納されていることがわかります。

print(result.stdout)
292 ns +- 4.24 ns per loop (mean +- std. dev. of 7 runs, 1000000 loops each)

この292 nsの部分を数値として扱えるように秒に変換してみます。

value, unit = result.stdout.split()[:2]
float(value) * {"s": 1, "ms": 1e-3, "us": 1e-6, "ns": 1e-9}[unit]
2.92e-07

%timeitに限らず、%%captureを使うとさまざまな出力をJupyter上から加工できます。よいJupyterライフを!

11
5
2

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
11
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?