[Tutor] Why does counting to 20 million stress my computer?
Dick Moores
rdm at rcblue.com
Sat Jul 17 05:17:50 CEST 2004
Danny Yoo wrote at 10:21 7/16/2004:
>An alternative solution is to use a while-loop, something like:
>
>###
>counter = 0
>while counter < 10:
> print "counter is:", counter
> counter = counter + 1
>###
>
>
>Using range() on large numbers is a common gotcha, so don't worry too much
>about not knowing about xrange(). There are a few things that work
>perfectly well on small things, but break down when the problem grows much
>larger; range() is one of those.
Thanks, Danny.
I found an egregious error in the spin.py I posted earlier. It had k
being augmented inside the range() loop. I took this line out, used
xrange() instead of range(), and for a speed comparison, added the loop
you suggested as another way.
Here are some results:
integer: 1000000 (1,000,000)
Counting..
0 to 1000000 in 0.141 seconds!
And now counting using a different loop..
0 to 1000000 in 0.406 seconds!
integer: 10000000 (10,000,000)
Counting..
0 to 10000000 in 1.500 seconds!
And now counting using a different loop..
0 to 10000000 in 4.016 seconds!
integer: 50000000 (50,000,000)
Counting..
0 to 50000000 in 7.188 seconds!
And now counting using a different loop..
0 to 50000000 in 19.110 seconds!
integer: 100000000 (100,000,000)
Counting..
0 to 100000000 in 15.078 seconds!
And now counting using a different loop..
0 to 100000000 in 40.204 seconds!
integer: 1000000000 (1,000,000,000)
Counting..
0 to 1000000000 in 148.859 seconds!
And now counting using a different loop..
0 to 1000000000 in 397.484 seconds!
Here's some info on my Dell desktop (thanks to Belarc Advisor):
2.80 gigahertz Intel Pentium 4
8 kilobyte primary memory cache
512 kilobyte secondary memory cache
Bus Clock: 533 megahertz
512 Megabytes Installed Memory
=======================================
#spin2.py
import time
print """
Enter an integer to count to from zero.
To quit, enter x or q.
"""
while True:
# for exiting via ^C or ^D
try:
max = raw_input("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) + 1
except:
print "That's not an integer!"
continue
print "Counting.."
tStart = time.time()
for k in xrange(max):
pass
tEnd = time.time()
print "0 to %d in %.3f seconds!" % (k, (tEnd - tStart))
print "And now counting using a different loop.."
c = 0
tStart = time.time()
while c < max -1 :
c += 1
tEnd = time.time()
print "0 to %d in %.3f seconds!" % (c, (tEnd - tStart))
================================
More information about the Tutor
mailing list