Capture the result of an IPython magic function

吃可爱长大的小学妹 提交于 2019-12-01 15:17:51

问题


I'm trying to capture the resulting object of IPython Notebook magic function. Specifically %timeit

So the following code...

import time
def say_hello(n):
    time.sleep(n)
    print "hello"

t = %timeit say_hello(5)

Prints to stdout:

1 loops, best of 3: 5 s per loop

However, I'd like to capture the result of %timeit say_hello(5) in the variable t.

A resulting object called TimeitResult is generated by %timeit, but I can't figure out how to access it from within a Notebook.

I'd like a cleaner solution than having to manually capture stdout using sys.stdout tricks (this code will be part of a presentation so I'm trying to keep it as straight forward as possible). Anyone have any ideas?


回答1:


In the source file you linked to, the docstring shows the options for running the timeit magic function; one of which is returning an object result:

-o: return a TimeitResult that can be stored in a variable to inspect
        the result in more details.

So, if you run

obj = %timeit -o somefunc()

obj will reference the result object that was returned (hint: use tab completion on the object, that will show you the attributes it has).




回答2:


An example of consuming the TimeItResult output:

myarray = (3,2,1)
sorttime = %timeit -n1 -r3 -o myarray.sort() 
print(sorttime.best)

Look here for the other TimeItResult attributes: https://ipython.org/ipython-doc/2/api/generated/IPython.core.magics.execution.html



来源:https://stackoverflow.com/questions/25289437/capture-the-result-of-an-ipython-magic-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!