range question, compared to Smalltalk

Bjorn Pettersen BPettersen at NAREX.com
Wed Aug 28 17:25:22 CEST 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):
            pass
        rtime = time.clock() - rstart
        
        xstart = time.clock()
        for i in xrange(count):
            pass
        xtime = time.clock() - xstart
        
        if rtime < xtime:
            winner = 'range'
        else:
            winner = 'xrange'
        print >> fp, '%8d %.3f %.3f %15s' % (count, rtime, xtime,
winner)
        
        
if __name__ == "__main__":
    fp = None
    if len(sys.argv) > 1:
        fp = open(sys.argv[1], 'w')
    rangeTest(fp)




More information about the Python-list mailing list