Why is subtraction faster than addition in Python?

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

    That would be remarkable, so I have thoroughly evaluated your code and also setup the expiriment as I would find it more correct (all declarations and function calls outside the loop). Both versions I have run five times.

    • Running your code validated your claims: -= takes constantly less time; 3.6% on average
    • Running my code, though, contradicts the outcome of your experiment: += takes on average (not always) 0.5% less time.

    To show all results I have put plots online:

    • Your evaluation: http://bayimg.com/kadAeaAcN
    • My evaluation: http://bayimg.com/KadaAaAcN

    So, I conclude that your experiment has a bias, and it is significant.

    Finally here is my code:

    import time
    
    addtimes = [0.] * 100
    subtracttimes = [0.] * 100
    
    range100 = range(100)
    range10000000 = range(10000000)
    
    j = 0
    i = 0
    x = 0
    start = 0.
    
    
    for j in range100:
     start = time.clock()
     x = 0
     for i in range10000000:
      x += 1
     addtimes[j] = time.clock() - start
    
    for j in range100:
     start = time.clock()
     x = 0
     for i in range10000000:
      x -= -1
     subtracttimes[j] = time.clock() - start
    
    print '+=', sum(addtimes)
    print '-=', sum(subtracttimes)
    

提交回复
热议问题