[Tutor] List comprehension question

Steven D'Aprano steve at pearwood.info
Tue Nov 9 21:54:24 CET 2010


Richard D. Moores wrote:

> See <http://tutoree7.pastebin.com/R82876Eg> for a speed test with n =
> 100,000 and 100,000 loops

As a general rule, you shouldn't try to roll your own speed tests. There 
are various subtleties that can throw your results right out. Timing 
small code snippets on modern multi-tasking computers is fraught with 
difficulties.

Fortunately Python comes with that battery already included: the timeit 
module. You can use it from the shell like this:

python -m timeit -s "setup code goes here" "test code goes here"

At the Python interactive interpreter, the most useful pattern I've 
found is:

from timeit import Timer
t = Timer("proper_divisors(n)",
     "from __main__ import proper_divisors; n = 100000")
min(t.repeat(repeat=5, number=100000))


Or if you're happy with Python's defaults, that last line can be just:

min(t.repeat())



-- 
Steven


More information about the Tutor mailing list