I ran some quick benchmarking using timeit.repeat
comparing two different ways to use an _accumulator_
.
def testAccumPlusEqual():
x = 0
for i in range(100):
x += 1
return x
def testAccumEqualPlus():
x = 0
for i in range(100):
x = x + 1
return x
My implementation of timeit.repeat
is:
if __name__ == '__main__':
import timeit
print(timeit.repeat("testAccumPlusEqual()",
setup="from __main__ import testAccumPlusEqual"))
print(timeit.repeat("testAccumEqualPlus()",
setup="from __main__ import testAccumEqualPlus"))
The results are found below:
>>>
[8.824021608811469, 8.80440620087051, 8.791231916848997]
[8.101681307351758, 8.143080002052649, 8.181129610882778]
Granted, in the grand scheme of things, this time difference may not be noticeable, but if used in large scale it could lead to a slow down. So I guess I'm really asking:
From everywhere I've seen, the de facto standard is to accumulate with +=
, but should that be the case still?
Why would +=
perform worse than x=x+
?
NOTE: Using CPython 3.3.2 on Windows 7 64bit(using 32bit version of python)