Can you capture the output of ipython's magic methods? (timeit)

Gus picture Gus · Jun 26, 2013 · Viewed 9.3k times · Source

I want to capture and plot the results from 5 or so timeit calls with logarithmically increasing sizes of N to show how methodX() scales with input.

So far I have tried:

output = %timeit -r 10 results = methodX(N)

It does not work...

Can't find info in the docs either. I feel like you should be able to at least intercept the string that is printed. After that I can parse it to extract my info.

Has anyone done this or tried?

PS: this is in an ipython notebook if that makes a diff.

Answer

Iguananaut picture Iguananaut · Aug 27, 2014

This duplicate question Capture the result of an IPython magic function has an answer demonstrating that this has since been implemented.

Calling the %timeit magic with the -o option like:

%timeit -o <statement>

returns a TimeitResult object which is a simple object with all information about the %timeit run as attributes. For example:

In [1]: result = %timeit -o 1 + 2
Out[1]: 10000000 loops, best of 3: 23.2 ns per loop

In [2]: result.best
Out[2]: 2.3192405700683594e-08