[Tutor] Why does counting to 20 million stress my computer?

Dick Moores rdm at rcblue.com
Wed Jul 21 07:26:19 CEST 2004


Alan Gauld wrote at 14:41 7/20/2004:
> > So xrange is definitely quicker. Is it better to use xrange all the
>time in
> > place of range then ?
>
>I haven't checked but my guess is that for small values range will be
>faster
>because it holds all the values in RAM and indexing will be faster
>than
>calculation.
>
>But if in doubt try it out...
>And tell us the result!
>
>Alan G.

Not sure if 1,000,000 and 10,000,000 are small values, but here's what I get:
positive integer: 1 (that's 1,000,000)
Counting using xrange()..
0 to 1000000 in 0.156 seconds!

positive integer: 10
Counting using xrange()..
0 to 10000000 in 1.485 seconds!

positive integer: 1
Counting using range()..
0 to 1000000 in 0.172 seconds!

positive integer: 10
Counting using range()..
0 to 10000000 in 1.766 seconds!

So xrange() has the edge.


I used this code, and switched from xrange() to range():

==============================
import time

while True:
     # for exiting via ^C or ^D
     try:
         max = raw_input("positive integer: ")
     except (TypeError, EOFError):
         print "Bye."
         break
     if len(max) == 0:
         print "Hey, don't just hit Enter, type an integer first!"
         continue
     if max in ["q", "x"]:
         print "Bye."
         break
     try:
         max = int(max) * 1000000 + 1
     except:
         print "That's not an integer!"
         continue
     if max <= 0:
         print "That's not a positive integer!"
         continue
     print "Counting using range().."
     tStart = time.time()
     for k in range(max):
         pass
     tEnd = time.time()
     print "0 to %d in %.3f seconds!" % (k, (tEnd - tStart))
==================================

Dick Moores



More information about the Tutor mailing list