I always read the code to calculate the time like this way:
%timeit function()
What does "%" mean here?
I think, the "%" is always used to replace something in a string, like %s means replace a string, %d replace a data, but I have no idea about this case.
%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 documentation:
To use it, for example if we want to find out whether using
xrange
is any faster than usingrange
, you can simply do:And you will get the timings for them.
The major advantages of
%timeit
are: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.It will automatically calculate number of runs required for your code based on a total of 2 seconds execution window.
You can make use of current console variables implicitly, whereas
timeit.timeit
requires them to be provided explicitly.