Why is subtraction faster than addition in Python?

后端 未结 10 1379
佛祖请我去吃肉
佛祖请我去吃肉 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:43

    "The second loop is reliably faster ..."

    That's your explanation right there. Re-order your script so the subtraction test is timed first, then the addition, and suddenly addition becomes the faster operation again:

    -= 3.05
    += 2.84
    

    Obviously something happens to the second half of the script that makes it faster. My guess is that the first call to range() is slower because python needs to allocate enough memory for such a long list, but it is able to re-use that memory for the second call to range():

    import time
    start = time.clock()
    x = range(10000000)
    end = time.clock()
    del x
    print 'first range()',end-start
    start = time.clock()
    x = range(10000000)
    end = time.clock()
    print 'second range()',end-start
    

    A few runs of this script show that the extra time needed for the first range() accounts for nearly all of the time difference between '+=' and '-=' seen above:

    first range() 0.4
    second range() 0.23
    

提交回复
热议问题