In interactive computing, magic commands can, for example, be used for simple profiling
tasks. For such a use case, you might use %time or %prun:
In [ 3 ]: import numpy as np
In [ 4 ]: %time np.sin(np.arange( 1000000 ))
CPU times: user 31.8 ms, sys: 7.87 ms, total: 39.7 ms
Wall time: 39 ms
Out[5]:
array([ 0. , 0.84147098, 0.90929743, ..., 0.21429647,
-0.70613761, -0.97735203])
In [ 6 ]: %prun np.sin(np.arange( 1000000 ))
3 function calls in 0.043 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.041 0.041 0.043 0.043 <string>: 1 (<module>)
1 0.002 0.002 0.002 0.002 {numpy.core.multiarray.arange}
1 0.000 0.000 0.000 0.000 {method ‘disable’
of ‘_lsprof.Profiler’ objects}
There is yet another command, %timeit or %%timeit, for timing codes in a single line or a
whole cell in the IPython Notebook:
In [6]: %timeit np.sin(np.arange(1000000))
10 loops, best of 3: 27.5 ms per loop
This function executes a number of loops to get more reliable estimates for the duration of
a function call or a snippet of code.
It is not possible to explain in detail all the magic functions that IPython provides.
However, IPython itself strives to make it as easy as possible to interactively look up
information about IPython and its commands. Among the most helpful are those listed in
Table 2-2. Selected help functions included in IPython
Name Description
?
Introduction and overview of IPython features
%quickref
Quick reference
help
Python’s own help system
object?
Details about the “object”; use object?? for extra details
Another feature of IPython is that it is highly configurable. Information about the
configuration capabilities is also found in the documentation.
A magic command that also helps with customizing IPython is %bookmark. This allows
the bookmarking of arbitrary directories by the use of your custom names such that you
can later — no matter where the IPython kernel is invoked from and no matter what the
current directory is — navigate to any of your bookmarked directories immediately (i.e.,
you do not need to use cd). The following shows how to set a bookmark and how to get a