%timeit
is an ipython magic function, which can be used to time a particular piece of code (A single execution statement, or a single method).
From the docs:
%timeit
Time execution of a Python statement or expression
Usage, in line mode:
%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
To use it, for example if we want to find out whether using xrange
is any faster than using range
, you can simply do:
In [1]: %timeit for _ in range(1000): True
10000 loops, best of 3: 37.8 μs per loop
In [2]: %timeit for _ in xrange(1000): True
10000 loops, best of 3: 29.6 μs per loop
And you will get the timings for them.
The major advantage of %timeit
are:
that you don't have to import timeit.timeit
from the standard library, and run the code multiple times to figure out which is the better approach.
%timeit will automatically calculate number of runs required for your code based on a total of 2 seconds execution window.
You can also make use of current console variables without passing the whole code snippet as in case of timeit.timeit
to built the variable that is built in an another environment that timeit works.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…