4

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.

Hich123
  • 41
  • 1
  • My guess: accessing variables in the global scope might be a wee bit slower than in a function scope. If you wrap all the stuff in version 2 into a function, it is much faster. – tobias_k Mar 13 '19 at 12:55
  • @tobias_k the op states that he has " two functions which are almost the same" and that "The first one is calling another function inside itself", so it _shouldn't_ be a global/local issue - but the snippet looks like top-lvel code indeed... – bruno desthuilliers Mar 13 '19 at 12:57
  • The snippets are not complete (no imports) but I'd still think that that code is global. At least I get the same results that way. – tobias_k Mar 13 '19 at 12:59

0 Answers0