pythonipythontimeitmagic-functionmagic-command

What is %timeit in Python?


I always read the code to calculate the time like this way:

%timeit function()

What does % mean here?

I think, % 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.


Solution

  • %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:

    %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 advantages of %timeit are: