Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 timeit.timeit expects, so combined with the single run requirement, I’d still go to timeit.timeit with a string setup and repeat it manually if lots of setup or a statistically higher precision is needed

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading