Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run an IPython magic from a script (or timing a Python script)

Tags:

python

ipython

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

like image 631
Ivan Oseledets Avatar asked Apr 28 '12 06:04

Ivan Oseledets


People also ask

What does %% time mean in Python?

%%time is a magic command. It's a part of IPython. %%time prints the wall time for the entire cell whereas %time gives you the time for first line only. Using %%time or %time prints 2 values: CPU Times.

Which is the command to run the script in IPython?

You can use run command in the input prompt to run a Python script. The run command is actually line magic command and should actually be written as %run. However, the %automagic mode is always on by default, so you can omit this.

What are magic commands in IPython?

The magic commands, or magics, are handy commands built into the IPython kernel that make it easy to perform particular tasks, for example, interacting Python's capabilities with the operating system, another programming language, or a kernel. IPython provides two categories of magics: line magics and cell magics.


1 Answers

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.

like image 192
user2261139 Avatar answered Sep 28 '22 17:09

user2261139