range question, compared to Smalltalk

Frank Buss fb at frank-buss.de
Wed Aug 28 18:13:40 CEST 2002


"Bjorn Pettersen" <BPettersen at NAREX.com> wrote:

> That, of course, depends <wink>. On my machine range is faster for lists
> up to ~1500 items and comparable to xrange up to ~17000 items... Test
> program below.

Do you know the german saying "Wer misst misst Mist" (who measures 
measures muck) ? :-)

Looks like it's highly optimized for loops and I can use it for this 
purpose.  But lets try this code:

import time
import random
rstart = time.clock()
for count in xrange(1, 10000): random.choice(range(count))
rtime = time.clock() - rstart
xstart = time.clock()
for count in xrange(1, 10000): random.choice(xrange(count))
xtime = time.clock() - xstart
if rtime < xtime:
  winner = 'range'
else:
  winner = 'xrange'
print '%8d %.3f %.3f %15s' % (count, rtime, xtime, winner)

The output on my computer:

9999 2.872 0.183          xrange

So xrange is 15 times faster than range for this example.

-- 
Frank Buß, fb at frank-buss.de
http://www.frank-buss.de, http://www.it4-systems.de



More information about the Python-list mailing list