0

So I was reading this question where the OP shows significant performance differences between the function scope and the global scope (~2x difference). I got excited and tried to reproduce the OP's results in two ways.

1. python script + terminal's time command

Function

def main():
    for i in xrange(10**8):
        pass
main()

real    0m2.040s
user    0m2.028s
sys 0m0.011s

Global

for i in xrange(10**8):
    pass

real    0m4.710s
user    0m4.699s
sys 0m0.010s

The second version is twice slower, which was expected.

2. ipython notebook

Function:

%%timeit
def main():
    for i in xrange(10**8):
        pass
main()
1 loops, best of 3: 2.15 s per loop

Global:

%%timeit
for i in xrange(10**8):
    pass
1 loops, best of 3: 2.14 s per loop

The two versions now show the same performance! What happened?

Community
  • 1
  • 1
usual me
  • 8,338
  • 10
  • 52
  • 95

1 Answers1

0

timeit runs all tests in a local namespace. The only difference in your case is that you added a function call, but both versions run with local names.

See the inner function template in the timeit module source; %(stmt)s is the code being repeatedly tested to get a good average time per execution.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343