Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a procedure is so much faster when put into a function?

Here is what I did, I created 2 procedures, one in a function and one in the python file itself. The one on the python file itself run almost 2 times slower even if it's exactly the same. WHY ?

Bellow is an example with 2 procedures that are just loops on P element

I have the following python file :

from time import *
P=1000000 #range of the 2 loops

def loop(N):
        for k in range(N):
                continue

start=time()
loop(P)
stop1=time()
for k in range(P):
            continue
stop2=time()
print "time with function ",stop1-start
print "time without function ",stop2-stop1

Here is what I get (I tried it with one thousand samples and the result is the following) :

time with function  0.0950000286102
time without function  0.15700006485

with xrange instead of range I get :

time with function  0.0460000038147
time without function  0.107999843597

So it's like 0.05 second in used to build the list

I know it's may be a useless question, but If someone know why is this going so much faster I would be happy to know

like image 249
Ricky Bobby Avatar asked Aug 11 '11 15:08

Ricky Bobby


People also ask

Which is faster function or procedure?

As you can see, the scalar functions are slower than stored procedures. In average, the execution time of the scalar function was 57 seconds and the stored procedure 36 seconds.

Why is a function better than a loop?

Just as a loop is an embodiment of a piece of code we wish to have repeated, a function is an embodiment of a piece of code that we can run anytime just by calling it into action. A given loop construct, for instance could only be run once in its present location in the source code.


1 Answers

The only significant difference is that the version in the function is only updating the local variable for that function, whereas the version not in a function is updating a global variable k.

As mentioned here:

The final speedup available to us for the non-map version of the for loop is to use local variables wherever possible. If the above loop is cast as a function, append and upper become local variables. Python accesses local variables much more efficiently than global variables.

like image 184
Amber Avatar answered Oct 22 '22 06:10

Amber