Why is subtraction faster than addition in Python?

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

    Is there a more general programming lesson here?

    The more general programming lesson here is that intuition is a poor guide when predicting run-time performance of computer code.

    One can reason about algorithmic complexity, hypothesise about compiler optimisations, estimate cache performance and so on. However, since these things can interact in non-trivial ways, the only way to be sure about how fast a particular piece of code is going to be is to benchmark it in the target environment (as you have rightfully done.)

提交回复
热议问题