[Tutor] List comprehension question
Steven D'Aprano
steve at pearwood.info
Fri Nov 12 11:11:04 CET 2010
Richard D. Moores wrote:
> I find using that at the interactive prompt a bit onerous -- lots of
> copy and pasting. And doubly so when comparing times for 2 or more
> functions.
Does your Python not support readline? Normally, if you press UP ARROW
or DOWN ARROW, Python will cycle through the previous interpreter lines.
Another approach is to write helper functions, or use string
interpolation, to make it easy to re-use code:
setup = "from __main__ import %s as func"
test = "func(1000)"
t1 = Timer(test, setup % "my_func")
t1 = Timer(test, setup % "your_func")
A third approach might be to treat your testing as a script. Put all
your test code in a module, and then run it:
python time_test.py
> The timeit doc gave me the obvious idea of how to avoid the prompt and
> also easily compare the times of 2 or more functions. I'd like to know
> if doing it this way is correct: Please see
> <http://tutoree7.pastebin.com/84u1fkgA>
You're vulnerable to statistical outliers (which are remarkably common
on multi-tasking operating systems!) cause by the OS calling some other
program in the middle of yours. Call each time test three or five times,
and use the smallest.
> Huh. Just realized that this timing method doesn't include the 5
> repeats called for by Steven's method. So how about using a for loop?
> As in <http://tutoree7.pastebin.com/J8bPKUqC>.
You're still re-inventing the wheel. timeit already includes a method
for doing exactly that: repeat. From the documentation:
def repeat(self, repeat=default_repeat, number=default_number):
"""Call timeit() a few times.
This is a convenience function that calls the timeit()
repeatedly, returning a list of results. ...
97% of the time you think you want to call timeit, you actually should
be calling min(timer.repeat()) instead.
--
Steven
More information about the Tutor
mailing list