Feb-23-2017, 03:53 PM
@Ofnuts, given the advice at https://wiki.python.org/moin/PythonSpeed...iding_dots... and my inability to find anything saying that CPython does any kind of optimization, I'm really doubtful of that. PyPy very well could.
(Feb-23-2017, 03:53 PM)micseydel Wrote: [ -> ]@Ofnuts, given the advice at https://wiki.python.org/moin/PythonSpeed...iding_dots... and my inability to find anything saying that CPython does any kind of optimization, I'm really doubtful of that. PyPy very well could.
import timeit,random class Counter(object): def __init__(self): self.someattribute=0 def runAttrib1(self,runs): self.someattribute=0 x=random.randint(1,10) for _ in range(runs): self.someattribute+=x return self.someattribute def runAttrib2(self,runs): self.someattribute=0 x=random.randint(1,10) for _ in range(runs): self.someattribute=self.someattribute+x return self.someattribute def runLocal(self,runs): self.someattribute=0 attribcopy=self.someattribute x=random.randint(1,10) for _ in range(runs): attribcopy+=x self.someattribute=attribcopy return x counter=Counter() number=1000 print ("%12s: %12.8f" % ('Attrib1',timeit.timeit(stmt='counter.runAttrib1(100000)',setup='from __main__ import counter', number=number))) print ("%12s: %12.8f" % ('Attrib2',timeit.timeit(stmt='counter.runAttrib2(100000)',setup='from __main__ import counter', number=number))) print ("%12s: %12.8f" % ('Local', timeit.timeit(stmt='counter.runLocal(100000)', setup='from __main__ import counter', number=number)))Output for Python2:
Output: Attrib1: 10.37185884
Attrib2: 8.38905406
Local: 5.44241190
Output for Python3:Output: Attrib1: 9.38220573
Attrib2: 8.99003031
Local: 4.89760979
So yes, some optimizations aren't done. Strangely var+=x
(Attrib1) is slower than var=var+x
(Attrib2)...