Cita:
Iniciado por razpeitia Aclaraciones:
Primera regla de la optimización en programación: No lo hagas.
Muy buena respuesta y ya que estamos, ¿dirías que ésta es una prueba "justa"?:
Código Python:
Ver original#loopfunctions.py
def fwhile(looplimit):
k=0
while k < looplimit:
k += 1
def frange(looplimit):
b = 0
for k in range(looplimit):
b += 1
def fxrange(looplimit):
b = 0
for k in xrange(looplimit):
b += 1
Código Python:
Ver original#loopfunctiontest.py
import timeit
import loopfunctions
def test_time_loops(looplimit,repeat_test,fn_calls):
print "looplimit: %d | test repetition: %d | function calls: %d\n" % (looplimit,repeat_test,fn_calls)
function0 = "fwhile(%d)" % looplimit
t0 = timeit.Timer(function0, "from loopfunctions import fwhile")
times0 = t0.repeat(repeat_test,fn_calls)
print "ffwhile time test \n max: %f\n min: %f\n typ: %f\n" % (max(times0),min(times0),sum(times0)/len(times0))
function1 = "frange(%d)" % looplimit
t1 = timeit.Timer(function1, "from loopfunctions import frange")
times1 = t1.repeat(repeat_test,fn_calls)
print "frange time test \n max: %f\n min: %f\n typ: %f\n" % (max(times1),min(times1),sum(times1)/len(times1))
function2 = "fxrange(%d)" % looplimit
t2 = timeit.Timer(function2, "from loopfunctions import fxrange")
times2 = t2.repeat(repeat_test,fn_calls)
print "fxrange time test \n max: %f\n min: %f\n typ: %f\n" % (max(times2),min(times2),sum(times2)/len(times2))
print "\nTest small arguments\n"
test_time_loops(200,5,1000)
print "-" * 20
print "\nTest big arguments\n"
test_time_loops(2000000,2,10)
#test_time_loops(sys.maxint,1,1)
Código consola:
Ver original>>>
Test small arguments
looplimit: 200 | test repetition: 5 | function calls: 1000
fwhile time test
max: 0.013561
min: 0.012781
typ: 0.013071
frange time test
max: 0.015569
min: 0.013655
typ: 0.014201
fxrange time test
max: 0.017101
min: 0.015968
typ: 0.016563
--------------------
Test big arguments
looplimit: 2000000 | test repetition: 2 | function calls: 10
fwhile time test
max: 1.327053
min: 1.308638
typ: 1.317846
frange time test
max: 1.873991
min: 1.761235
typ: 1.817613
fxrange time test
max: 1.211450
min: 1.202643
typ: 1.207047
>>>