Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
捕获IPython魔术函数的结果_Python_Ipython_Ipython Magic - Fatal编程技术网

捕获IPython魔术函数的结果

捕获IPython魔术函数的结果,python,ipython,ipython-magic,Python,Ipython,Ipython Magic,我试图捕捉IPython笔记本神奇函数的结果对象。特别是%timeit 所以下面的代码 import time def say_hello(n): time.sleep(n) print "hello" t = %timeit say_hello(5) 打印到标准输出: 1 loops, best of 3: 5 s per loop 但是,我想在变量t中捕获%timeit say_hello(5)的结果 名为的结果对象由%timeit生成,但我不知道如何从笔记本中访问它

我试图捕捉IPython笔记本神奇函数的结果对象。特别是
%timeit

所以下面的代码

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

t = %timeit say_hello(5)
打印到标准输出:

1 loops, best of 3: 5 s per loop
但是,我想在变量
t
中捕获
%timeit say_hello(5)
的结果

名为的结果对象由
%timeit
生成,但我不知道如何从笔记本中访问它


我想要一个更干净的解决方案,而不是使用
sys.stdout
技巧手动捕获stdout(此代码将作为演示文稿的一部分,因此我尝试尽可能直接地保存它)。有人有什么想法吗?

在链接到的源文件中,docstring显示了运行timeit magic函数的选项;其中之一是返回对象结果:

-o: return a TimeitResult that can be stored in a variable to inspect
        the result in more details.
所以,如果你跑

obj = %timeit -o somefunc()

obj
将引用返回的结果对象(提示:在对象上使用制表符完成,这将显示其属性)。

使用TimeItResult输出的示例:

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

在此处查找其他TimeItResult属性:

补充@dsemi的答案:使用
-o
timeit
结果保存到变量中,例如:

obj = %timeit -o somefunc()
当使用制表符完成时,
TimeitResult
的docstring文档显示可用属性:

Object returned by the timeit magic with info about the run.

Contains the following attributes :

loops: (int) number of loops done per measurement
repeat: (int) number of times the measurement has been repeated
best: (float) best execution time / number
all_runs: (list of float) execution time of each run (in s)
compile_time: (float) time of statement compilation (s)

你想要输出的字符串,还是TimeitResult对象?可能是Awesome的副本,这正是我想要的!是否有
TimeitResult
对象的文档,这样我就不必使用制表符完成技巧,自己计算所有属性?找不到任何正式文档,但中的文档字符串显示所有属性。