Why is subtraction faster than addition in Python?

后端 未结 10 1364
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 12:59

I was optimising some Python code, and tried the following experiment:

import time

start = time.clock()
x = 0
for i in range(10000000):
    x += 1
end = tim         


        
相关标签:
10条回答
  • 2020-12-13 13:50

    Your experiment is faulty. The way this experiment should be designed is to write 2 different programs - 1 for addition, 1 for subtraction. They should be exactly the same and run under the same conditions with the data being put to file. Then you need to average the runs (at least several thousand), but you'd need a statistician to tell you an appropriate number.

    If you wanted to analyze different methods of addition, subtraction, and looping, again each of those should be a separate program.

    Experimental error might arise from heat of processor and other activity going on the cpu, so i'd execute the runs in a variety of patterns...

    0 讨论(0)
  • 2020-12-13 13:51

    The running loop backwards is faster because the computer has an easier time comparing if a number is equal to 0.

    0 讨论(0)
  • 2020-12-13 13:54
    $ python -m timeit -s "x=0" "x+=1"
    10000000 loops, best of 3: 0.151 usec per loop
    $ python -m timeit -s "x=0" "x-=-1"
    10000000 loops, best of 3: 0.154 usec per loop
    

    Looks like you've some measurement bias

    0 讨论(0)
  • 2020-12-13 13:56

    With Python 2.5 the biggest problem here is using range, which will allocate a list that big to iterate over it. When using xrange, whichever is done second is a tiny bit faster for me. (Not sure if range has become a generator in Python 3.)

    0 讨论(0)
提交回复
热议问题