问题
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
python -Q command line argument
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