range question, compared to Smalltalk

Bjorn Pettersen BPettersen at NAREX.com
Wed Aug 28 11:25:22 EDT 2002

> From: Frank Buss [mailto:fb at frank-buss.de] 
> Neal Norwitz <neal at metaslash.com> wrote:
> > Use xrange.  But xrange only works on integer values defined by a C 
> > long (usually 32 bits, but sometimes 64 bits).
> Thanks, that's what I was searching for. Because it is a 
> builtin type it's 
> faster than a solution with a normal Python class, I assume, 
> and it should 
> be used for loops ("for i in xrange(123):") every time, 
> shouldn't it? 

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.

-- bjorn

import sys
import time

def rangeTest(fp=None):
    for count in xrange(sys.maxint):
        rstart = time.clock()
        for i in range(count):
        rtime = time.clock() - rstart
        xstart = time.clock()
        for i in xrange(count):
        xtime = time.clock() - xstart
        if rtime < xtime:
            winner = 'range'
            winner = 'xrange'
        print >> fp, '%8d %.3f %.3f %15s' % (count, rtime, xtime,
if __name__ == "__main__":
    fp = None
    if len(sys.argv) > 1:
        fp = open(sys.argv[1], 'w')

More information about the Python-list mailing list