Capture the result of an IPython magic function

后端 未结 3 443
时光取名叫无心
时光取名叫无心 2021-01-17 11:54

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

So the following code...

import tim         


        
相关标签:
3条回答
  • 2021-01-17 12:38

    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).

    0 讨论(0)
  • 2021-01-17 12:40

    Complementing @dsemi's answer: Use -o to save the timeit result into a variable, e.g.:

    obj = %timeit -o somefunc()
    

    The docstring documentation of the TimeitResult when using tab completion shows the available attributes:

    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)
    
    0 讨论(0)
  • 2021-01-17 12:52

    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

    0 讨论(0)
提交回复
热议问题