Does Python optimize low-power functions?

Nick Cash nick.cash at npcinternational.com
Fri Dec 6 14:32:00 EST 2013


>My question is, what do Python interpreters do with power operators where the power is a small constant, like 2?  Do they know to take the shortcut?

Nope:

Python 3.3.0 (default, Sep 25 2013, 19:28:08) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import dis
>>> dis.dis(lambda x: x*x)
  1           0 LOAD_FAST                0 (x) 
              3 LOAD_FAST                0 (x) 
              6 BINARY_MULTIPLY      
              7 RETURN_VALUE         
>>> dis.dis(lambda x: x**2)
  1           0 LOAD_FAST                0 (x) 
              3 LOAD_CONST               1 (2) 
              6 BINARY_POWER         
              7 RETURN_VALUE         


The reasons why have already been answered, I just wanted to point out that Python makes it extremely easy to check these sorts of things for yourself.



More information about the Python-list mailing list