while True or while 1
Ethan Furman
ethan at stoneleaf.us
Thu Dec 16 10:36:10 EST 2010
BartC wrote:
> "Steve Holden" <steve at holdenweb.com> wrote in message
> news:mailman.462.1292214062.2649.python-list at python.org...
>> On 12/12/2010 2:32 PM, Christian Heimes wrote:
>>> Am 12.12.2010 19:31, schrieb Steve Holden:
>>> $ python -m timeit -n20 -- "i = 0" "while 1:" " i+=1" " if i ==
>>> 1000000: break"
>>> 20 loops, best of 3: 89.7 msec per loop
>>> $ python -m timeit -n20 -- "i = 0" "while True:" " i+=1" " if i ==
>>> 1000000: break"
>>> 20 loops, best of 3: 117 msec per loop
>
>>> No argue with that! I was merely making a point that "while 1" executes
>>> different byte code than "while True". Readability is important but
>>> sometimes speed is of the essence. "while 1" is one of the few tricks to
>>> speed up tight loops a bit.
>>
>> OK, but the figures you quote save you 27.3 ms per million iterations,
>> for a grand total saving of 27.3 ns per iteration. So "a bit" is hardly
>> worth considering for most programs, is it?
>
> One these is 30% faster than the other. That's an appreciable
> difference, which you can't really just dismiss.
Anecdotal evidence says it is easily dismissed:
I had a routine that processed records from a table using custom, on the
fly, code. I could either use exec for each record to do the work, or
create a function that would then be called. I timed exec vs function,
and found the function style to be about 200% faster... Eureka!, I
thought. After putting the functional method in place, a run that took
about 16 minutes using the old exec method ran two (2!) seconds faster.
Great learning experience, for both the function method (which I
prefer), and the need for profiling.
~Ethan~
More information about the Python-list
mailing list