1

I stumbled upon something which makes no sense. I have this python code which does 2 simple for-loops and just measures the execution time. However I discovered that the exact same code called from a function takes half of the time. Can someone explain why ?

print "no function"

start_time = time.time()
for i in range(10000):
    for j in range(10000):
        z = i*j
print z
print("--- %s seconds ---" % (time.time() - start_time))

# VS

def Function():
    start_time = time.time()
    for i in range(10000):
        for j in range(10000):
            z = i*j
    print z
    print("--- %s seconds ---" % (time.time() - start_time))

print "Function Call"
Function()

And here is the output:

no function
99980001
--- 8.89359378815 seconds ---
Function Call
99980001
--- 4.64798092842 seconds ---
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Alex
  • 550
  • 1
  • 7
  • 19
  • Without testing and taking an uneducated guess, I would say that acessing locals is much faster than globals because they can be somewhat optimized (acessed by index rather than name). – Niklas R Aug 14 '16 at 12:15
  • The difference is in the scope of variables and their lookup times. – Oleg Sklyar Aug 14 '16 at 12:17
  • You are both right, apparently the question was already answered here anyway http://stackoverflow.com/questions/11241523/why-does-python-code-run-faster-in-a-function – Alex Aug 14 '16 at 12:25

1 Answers1

1

From PythonInSpeed website we can read this:

In functions, local variables are accessed more quickly than global variables, builtins, and attribute lookups. So, it is sometimes worth localizing variable access in inner-loops. For example, the code for random.shuffle() localizes access with the line, random=self.random. That saves the shuffling loop from having to repeatedly lookup self.random. Outside of loops, the gain is minimal and rarely worth it.

BPL
  • 9,632
  • 9
  • 59
  • 117