It's well known that Jupyter / IPython can measure execution time with % time
and% timeit
, but have you ever wanted to process or visualize this?
You can use %% capture
to treat standard output as a Python object.
Let's actually do it.
%%capture result
%timeit 2 ** 100
The argument of %% capture
is the object name, please refer to the help for other options.
%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.
If you look at the stdout
attribute, you can see that the standard output is stored in a string.
print(result.stdout)
292 ns +- 4.24 ns per loop (mean +- std. dev. of 7 runs, 1000000 loops each)
Let's convert this 292 ns
part into seconds so that it can be treated as a numerical value.
value, unit = result.stdout.split()[:2]
float(value) * {"s": 1, "ms": 1e-3, "us": 1e-6, "ns": 1e-9}[unit]
2.92e-07
Not limited to % timeit
, you can use %% capture
to process various outputs from Jupyter. Have a good Jupyter life!
Recommended Posts