2

Okay, so the wording of this question is very hard to say.

However, I have two scripts written in Python 3.5.2:

import time
t0 = time.clock()
def hello():
    a = []
    for i in range(10000000):
        a.append(i)
hello()
t1 = time.clock()
print((t1-t0))

Out: 1.0960211284655088

and

import time
t0 = time.clock()
a = []
for i in range(10000000):
    a.append(i)
t1 = time.clock()
print((t1-t0))

Out: 1.432725885821128

The first script runs faster being inside a defined function and then called; however, I don't know why this is and I would like to understand so I can learn to optimize code.

This is a question regarding only this particular aspect of Python 3. I know list comprehensions and map() are much, much faster and more pythonic methods of doing this particular iteration.

dysfunctional
  • 131
  • 2
  • 7
  • Independent of your quest to optimize performance, I feel that it's *ALWAYS* better to put your code in functions than place it at file scope. It makes to easier to turn the script into a reusable module and also makes the code easier to understand for people inheriting your stuff after you've moved on to a new job. Personally, I think even a main script should have no code at file scope other than: if __name__ == '__main__': callToEntryFunction() P.S. Sorry, can't figure out how to format code in a comment. :-\ – antred Sep 29 '16 at 06:13
  • I completely agree. However, for quick hacking with python (like with jupyter as an example). If looking through a large amount of data in Python, it might be faster (performance wise) to throw it into a function.. Of course, you could always just use R or Julia lol; but that's off-topic. – dysfunctional Sep 29 '16 at 06:20

1 Answers1

0

In my opinion. the difference is caused by the search for variable a. if a is local, the function will find it quickly and do append. if a is global, the function first will search a in local, and then search in global. that's why costs more time.

Howardyan
  • 667
  • 1
  • 6
  • 15
  • I had the same idea, and tested that by putting `a = []` in the global context and adding `global a` to the implementation of `hello()`. Didn't change a thing. – Jan Christoph Terasa Sep 29 '16 at 04:33
  • `i` is in the local context too, what about that? – Chris Martin Sep 29 '16 at 04:51
  • In the Python data structures is there something that talks about functions running with different C code backing them versus running scripts outside the scope of a function? Perhaps overhead in defining what 'a' is? – dysfunctional Sep 29 '16 at 04:57