Why is the procedure much faster when entering the function?

Here is what I did, I created 2 procedures, one in the function and one in the python file itself. One of the python files runs almost 2 times slower, even if it is exactly the same. WHAT FOR?

Below is an example with two procedures that are just loops on an element P

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 a thousand samples, and the result is as follows):

 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 looks like 0.05 seconds when using a list

I know this may be a useless question, but if someone knows why this is happening much faster, I would be happy to know

+8
performance python local-variables
source share
1 answer

The only significant difference is that the version in the function only updates the local variable for this function, while the version in the function does not update the global variable k .

As mentioned here :

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

+14
source share

All Articles