while True or while 1

BartC bc at freeuk.com
Thu Dec 16 18:34:21 EST 2010


"Steve Holden" <steve at holdenweb.com> wrote in message
news:mailman.54.1292502247.6505.python-list at python.org...
> 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.

> sholden at lifeboy ~
> $ python -m timeit -- "i = 1" "while True:" "    i += 1" "    if i ==
> 1000000: break"
> 10 loops, best of 3: 157 msec per loop

> $ python -m timeit -- "i = 1" "while 1:" "    i += 1" "    if i ==
> 1000000: break"
> 10 loops, best of 3: 116 msec per loop

I used a single loop counting to 10 million, and the timings were roughly
2.5xx and 1.8xx seconds, on Python 2.5 (1.35 and 1.05 seconds inside a
function).

In terms of a more realistic function (admittedly still a little contrived, 
as the loop would be written differently), I tried this:

def p2(n):
  p=1
  while True:
    if n<=p: return p
    p<<=1
  return 0

for i in xrange(1000000):
  x=p2(i)

p2() calculates the smallest power of 2 >= it's operand.

Using while True as shown, it took 3.4 seconds. Using While 1, it took 2.6 
seconds (Python 2.5).

-- 
Bartc 




More information about the Python-list mailing list