while True or while 1
Steve Holden
steve at holdenweb.com
Sun Dec 12 23:20:40 EST 2010
On 12/12/2010 2:32 PM, Christian Heimes wrote:
> Am 12.12.2010 19:31, schrieb Steve Holden:
>> > Would you care to quantify how much CPU time that optimization will
>> > typically save for a loop of fair magnitude (say, a billion iterations)?
> The difference is minimal but measurable for very tight loops.
>
> $ 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
>
> In Python 2.x the peep hole optimizer can't remove the global lookup and
> check for trueness for "while True".
>
Yes, you said that already and I certainly didn't disagree.
[...]
>> Python is designed to provide readable code. Writing
>> >
>> > while True:
>> > ...
>> >
>> > is much more legible than its pre-True couterpart
>> >
>> > while 1:
>> > ...
> 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?
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon 2011 Atlanta March 9-17 http://us.pycon.org/
See Python Video! http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list
mailing list