i was working on a project and i noticed something odd (at least for me). i have two functions which are almost the same.
The first one is calling another function inside itself
def sumnew(i):
mysum=0
for j in range(1,i+1):
mysum=mysum+1
return mysum
counter=5000
start=datetime.datetime.now()
numberofiterations=0
for i in range (1,counter+1):
numberofiterations=numberofiterations+ sumnew(i)
print ("the number of iteration is :" + str(numberofiterations))
print ("calculation time: " + str((datetime.datetime.now()-start).total_seconds()) + " seconds")
the number of iteration is :12502500 calculation time: 0.525 seconds
The second one just hold the whole code inside one function.
counter=5000
start=datetime.datetime.now()
numberofiterations=0
for i in range (1,counter+1):
mysum=0
for j in range(1,i+1):
mysum=mysum+1
numberofiterations=numberofiterations+mysum
print ("the number of iteration is :" + str(numberofiterations))
print ("calculation time: " + str((datetime.datetime.now()-start).total_seconds()) + " seconds")
the number of iteration is :12502500 calculation time: 0.91 seconds
I would have expected the first function to be slower, yet it seems to be ~two times faster, would you have any idea why?
Thanks for sharing your wisdom!
P.S, i realise the code is inefficient, i simplified it to highlight my question.