How does this internal Python optimization work for math expressions?

This is an optimization issue. I have an expression inside a function like:

>>> def x():
...     num = 2 * 4 * 100 * 20
...
>>> x.__code__.co_consts
(None, 2, 4, 100, 20, 8, 800, 16000)

The result of the expression 2 * 4 * 100 * 20is equal 16000, therefore, if we break it down x:

>>> dis.dis(x)
  2           0 LOAD_CONST               7 (16000)
              3 STORE_FAST               0 (x)
              6 LOAD_CONST               0 (None)
              9 RETURN_VALUE       

16,000 is pretty much what you need. co_constsstores 8 and 800, which are technically not needed anymore, do we have a total amount or are they?

Comparing the above expression with another:

>>> def x():
...     num = 3 + 4 + 9  * 4
... 
>>> x.__code__.co_consts
(None, 3, 4, 9, 7, 36)

it looks like this: the bytecode compiler accepts binary operands and saves its calculation values:

9 * 4   36 
3 + 4   7 

function parsing:

>>> dis.dis(x)
  2           0 LOAD_CONST               4 (7)
              3 LOAD_CONST               5 (36)
              6 BINARY_ADD          
              7 STORE_FAST               0 (num)
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE   

Interestingly, if you accept this expression 2 + 5 * 8 - 5 + 23 * 4, co_constsit will (None, 2, 5, 8, 23, 4, 40, 92)only multiply were calculated: 5 * 8and 23 * 4the addition and subtraction were ignored.

? 2.7.

+4
1

;-) , , . , " " , -. , , , . , Python 3.6.1:

>>> def f():
...     return 2 + 5 * 8 - 5 + 23 * 4
>>> f.__code__.co_consts
(None, 2, 5, 8, 23, 4, 40, 42, 37, 92, 129)
>>> import dis
>>> dis.dis(f)
  2           0 LOAD_CONST              10 (129)
              2 RETURN_VALUE

, , .

@COLDSPEED , , peephole.c, CPython, . , .

+4

Source: https://habr.com/ru/post/1682045/


All Articles