Search code examples
pythonipythontiming

iPython timeit - only time part of the operation


I was attempting to determine, via iPython's %%timeit mechanism, whether set.remove is faster than list.remove when a conundrum came up.

I could do

In [1]: %%timeit
a_list = list(range(100))
a_list.remove(50)

and then do the same thing but with a set. However, this would include the overhead from the list/set construction. Is there a way to re-build the list/set each iteration but only time the remove method?


Solution

  • Put your setup code on the same line to create any names or precursor operations you need!
    https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit

    In cell mode, the statement in the first line is used as setup code (executed but not timed) and the body of the cell is timed. The cell body has access to any variables created in the setup code.

    %%timeit setup_code
    ...
    

    Unfortunately only a single run can be done as it does not re-run the setup code

    %%timeit -n1 x = list(range(100))
    x.remove(50)
    

    Surprisingly, this doesn't accept a string like the timeit module, so combined with the single run requirement, I'd still defer to timeit with a string setup= and repeat it if lots of setup or a statistically higher precision is needed

    See @Kelly Bundy's much more precise answer for more!