Why is integer divisions not optimised when compiling to bytecode?

那年仲夏 提交于 2020-01-24 07:48:07

问题


First, let me show a experiment I do:

In [69]: dis.dis(lambda : 4 / 2 +  1.5 * 2 + (4 - 2))
  1           0 LOAD_CONST               1 (4)
              3 LOAD_CONST               2 (2)
              6 BINARY_DIVIDE       
              7 LOAD_CONST               4 (3.0)
             10 BINARY_ADD          
             11 LOAD_CONST               5 (2)
             14 BINARY_ADD          
             15 RETURN_VALUE 

As you can see in the output of dis.dis, 1.5 * 2 and 4 - 2 get compiled to LOAD_CONST instead of two LOAD_CONST followed by a binary operation.

But 4 / 2 is not replaced with something like LOAD_CONST 4 (2).

I wonder why is division left out in the optimisation.

The version of Python I use is 2.7.5.

BTW, it seems that in Python 3, functions like this get better optimizations, here's what I see:

>>> dis.dis(lambda : 4 / 2 +  1.5 * 2 + (4 - 2))
  1           0 LOAD_CONST               8 (7.0)
              3 RETURN_VALUE

回答1:


Because division can be controlled by the following factors

  1. python -Q command line argument

  2. from __future__ import division

which will not be available to the peephole optimizer at the compile time.

This is explained in the source code of peephole



来源:https://stackoverflow.com/questions/23031282/why-is-integer-divisions-not-optimised-when-compiling-to-bytecode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!