The IPython %timeit magic command does its job well for measuring time required to run some Python code. Now, I want to use something analogous in the Python script. I know about the timeit module, however, it has several disadvantages, for example, how to select the number of runs adaptively? i.e., the default code
import timeit
t=timeit.Timer("code(f)", "from __main__ import code,f")
t.timeit()
runs the code million times. The %timeit IPyhton magic command does it automatically. I suggest that I could use something like the MATLAB code
http://www.mathworks.com/matlabcentral/fileexchange/18798
that does all the job automatically (and also tells if the overhead of the function is large).
How can I call %timeit magic from a Python script (or maybe there is a better timing solution) ?
解决方案
It depends a bit on which version of IPython you have. If you have 1.x:
from IPython import get_ipython
ipython = get_ipython()
If you have an older version:
import IPython.core.ipapi
ipython = IPython.core.ipapi.get()
or
import IPython.ipapi
ipython = IPython.ipapi.get()
Once that's done, run a magic command like this:
ipython.magic("timeit abs(-42)")
Note that the script must be run via ipython.