aList=[]
loop=1
try:
while loop <= 20000001:
aList.append(loop)
loop = loop + 1
except MemoryError:
print "Memory is out of scope."
import sys
sys.exit()
loop=1
try:
while loop <= 20000001:
aList.append(loop)
loop = loop + 1
except MemoryError:
print "Memory is out of scope."
import sys
sys.exit()
aTuple=tuple(aList)
evenNumber1 = 0
oddNumber1 = 0
import time
startTime1=time.time()
for i in aTuple:
#i is an even number
if not i % 2:
evenNumber1 = evenNumber1 + 1
#i is an odd number
if i % 2:
oddNumber1 = oddNumber1 + 1
print "Total number are %s" % len(aTuple)
print "even number are %s" % evenNumber1
print "odd number are %s" % oddNumber1
print "Costed time are %s seconds" % round((time.time() - startTime1),3)
oddNumber1 = 0
import time
startTime1=time.time()
for i in aTuple:
#i is an even number
if not i % 2:
evenNumber1 = evenNumber1 + 1
#i is an odd number
if i % 2:
oddNumber1 = oddNumber1 + 1
print "Total number are %s" % len(aTuple)
print "even number are %s" % evenNumber1
print "odd number are %s" % oddNumber1
print "Costed time are %s seconds" % round((time.time() - startTime1),3)
evenNumber2 = 0
oddNumber2 = 0
startTime2=time.time()
for x in aList:
#x is an even number
if not x % 2:
evenNumber2 = evenNumber2 + 1
#x is an odd number
if x % 2:
oddNumber2 = oddNumber2 + 1
oddNumber2 = 0
startTime2=time.time()
for x in aList:
#x is an even number
if not x % 2:
evenNumber2 = evenNumber2 + 1
#x is an odd number
if x % 2:
oddNumber2 = oddNumber2 + 1
print "\nTotal number are %s" % len(aList)
print "even number are %s" % evenNumber2
print "odd number are %s" % oddNumber2
print "Costed time are %s seconds" % round((time.time() - startTime2),3)
print "even number are %s" % evenNumber2
print "odd number are %s" % oddNumber2
print "Costed time are %s seconds" % round((time.time() - startTime2),3)
测试结果:
元组:
Total number are 20000001
even number are 10000000
odd number are 10000001
Costed time are 8.437 seconds
even number are 10000000
odd number are 10000001
Costed time are 8.437 seconds
列表:
Total number are 20000001
even number are 10000000
odd number are 10000001
Costed time are 9.064 seconds
even number are 10000000
odd number are 10000001
Costed time are 9.064 seconds