On 12/16/2010 7:23 AM, Steve Holden wrote:
On 12/16/2010 5:44 AM, BartC wrote:
One these is 30% faster than the other. That's an appreciable
difference, which you can't really just dismiss.
And you can't tell what the overall effect on a program will be: perhaps
the loop will be in a library function , which might be called billions
of times.
It might. But if the code it is calling does *anything* at all
significant I can promise you that spending an extra 30% purely on the
looping construct will still make a negligible difference to a program's
execution time, and there are almost certainly going to be many other
aspects of performance that will yield greater benefits from tuning.
I realise that there are going to be some people who just flatly say
"since 'while 1:' is quicker I am going to use it every time", and that
their programs will still work. And I still maintain that (for English
speakers) "while True:" is to be preferred.
shol...@lifeboy ~
$ python -m timeit -- "i = 1" "while True:" " i += 1" " if i ==
1000000: break"
10 loops, best of 3: 157 msec per loop
shol...@lifeboy ~
$ python -m timeit -- "i = 1" "while True:" " i += 1" " if i ==
1000000: break" " x = i+1"
10 loops, best of 3: 238 msec per loop
shol...@lifeboy ~
$ python -m timeit -- "i = 1" "while 1:" " i += 1" " if i ==
1000000: break"
10 loops, best of 3: 116 msec per loop
shol...@lifeboy ~
$ python -m timeit -- "i = 1" "while 1:" " i += 1" " if i ==
1000000: break" " x = i+1"
10 loops, best of 3: 195 msec per loop
This are all Python2 timings.
If binding a simple arithmetic expression adds more to the loop than the
difference between "while 1:" and "while True:" you are wasting your
time thinking about the savings under all but the most rigorous
circumstances.
*Especially* when the 'problem' has been fixed in Python 3.
--
Terry Jan Reedy
--
http://mail.python.org/mailman/listinfo/python-list