I've been trying to understand Python for loop performance, here I found that for loop with same iterations in global space is taking much time compared with one inside a function.
import time
MAX_NUM = 50000000
# Running for loop in global space
start = time.time()
for i in xrange(MAX_NUM):
pass
print time.time() - start
# Running th same kind of loop within a function
def foo():
for i in xrange(MAX_NUM):
pass
start = time.time()
foo()
print time.time() - start
When I execute this I've witnessed a huge difference in execution times.
2.00527501106
0.811304092407
I'm wondering that what makes this huge difference in execution time? how for loop performance affects from global space to write inside a function?