Search code examples
pythonperformancepython-3.xprocessing-efficiency

Is doing multiplication multiple times or assigning to a variable faster?


Let's say I have this code:

foo = int(input("Number"))
bar = int(input("Number"))
for number in range(0, 10):
    if foo*bar > 0:
        print("hello")

But, I could also have this code:

foo = int(input("Number"))
bar = int(input("Number"))
top = foo*bar
for number in range(0, 10):
    if top > 0:
        print("hello")

Which one is faster?

Using Python 3.


I realize that this question is similar, however, it's for Java, and Python may be different. Additonally, they're asking about memory efficiency whereas I am asking about processor efficiency.


Solution

  • Just so we can end this already, here is the answer. Using timeit on my computer we get the results as...

    Do the multiplication in the loop every time:

    $ python -m timeit 'for _ in xrange(10): 10 * 20 > 0'
    1000000 loops, best of 3: 1.3 usec per loop
    

    Do the multiplication outside the loop:

    $ python -m timeit 'foo = 10 * 20
    > for _ in xrange(10): foo > 0'
    1000000 loops, best of 3: 1.07 usec per loop
    

    Running the multiplication outside the loop instead of inside of it saves us 0.23 microseconds - about 18%.

    Note that I'm using Python 2.7.10 on a 2007 iMac (2.4 GHz) running OS X 10.11.0, developer preview 7. Your exact results may vary with Python version, hardware, OS Version, CPU... other applications you have running (just Safari with 3 tabs in my case). But you should comparably see that storing the number in a variable is trivial compared to repeatedly performing the same operation and discarding the results every time.

    In the future, OP, please just use timeit. It comes built in with Python for doing performance checks just like this. See the documentation here: https://docs.python.org/3/library/timeit.html (On that note, do not fear the documentation. Read them. If you have questions, ask them on Stack Overflow - you may reveal short-comings in the documentation where they need to be improved/clarified. Or at the very least, your questions will be answered and you'll know more afterwards than you did before.)