29

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.

Gus
  • 691
  • 1
  • 8
  • 12
  • possible duplicate of [Capture the result of an IPython magic function](http://stackoverflow.com/questions/25289437/capture-the-result-of-an-ipython-magic-function) – Iguananaut Aug 27 '14 at 16:28

2 Answers2

48

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
Community
  • 1
  • 1
Iguananaut
  • 21,810
  • 5
  • 50
  • 63
  • This seems specific to only some magic commands (maybe just `%timeit`?). It does not work with `%%timeit`. Using `result = %%timeit -o` as the line of a cell returns `None`. – Steven C. Howell May 05 '17 at 20:54
  • 8
    @StevenC.Howell You can use `%%timeit -o` without assignment. It will return a `TimeitResult` object and thanks to IPython's output capture you can retrieve the result by accessing `_`. – lovetl2002 Aug 24 '17 at 06:18
  • From the docs for `timeit` : "In cell mode (%%timeit) the statement in the first line is used as setup code (executed but not timed) and the body of the cell is timed. The cell body has access to any variables created in the setup code." https://github.com/ipython/ipython/blob/4581d8b93c42014c0c232ac5de169dad053ea809/IPython/core/magics/execution.py#L876 – Davos Jul 22 '19 at 11:12
  • 2
    Additionally, if you add `-q` the you don't the normal output. – coderforlife Jul 16 '20 at 22:09
1

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

No it does not.

On dev there is te %%capture cell magic. The other way would be to modify the timeit magic to return value instead of printing, or use the timeit module itself. Patches welcomed.

Matt
  • 27,170
  • 6
  • 80
  • 74