Time python scripts using IPython magic

user1507844 picture user1507844 · Jul 29, 2014 · Viewed 12k times · Source

How can I time the execution of a Python script using the iPython %time or %%timeit magic commands? For example, I have script.py and I'd like to know how long it takes to execute. Small nuance: script.py needs input parameter(s). The below doesn't seem to work.

%%time script.py input_param1 input_param2

Answer

user2304916 picture user2304916 · Jul 29, 2014

Solution

Your can use:

%%timeit
%run script.py input_param1 input_param2

beware that the script will be executed multiple times (the number is adaptive). To execute it only once (and have less accurate timing) change the first line to

%%timeit -n1 -r1

Explanation

All the magic commands starting with %% apply to the whole cell. In particular %%timeit will time all the lines in the cell.

IPython allows to use magic commands (single %) in any point of your code (i.e. loops, if-then). Here we just use the magic command %run to run the script.

See also: Magic functions from the official IPython docs.