因为窥视孔优化器通过预先计算乘法的结果来优化它import dis
dis.dis(compile("10 / float(98765)", "", "eval"))
1 0 LOAD_CONST 0 (10)
3 LOAD_NAME 0 (float)
6 LOAD_CONST 1 (98765)
9 CALL_FUNCTION 1
12 BINARY_DIVIDE
13 RETURN_VALUE
dis.dis(compile("10 / (98765 * 1.0)", "", "eval"))
1 0 LOAD_CONST 0 (10)
3 LOAD_CONST 3 (98765.0)
6 BINARY_DIVIDE
7 RETURN_VALUE
它将98765 * 1.0的结果作为常量值存储在字节码中。所以,它只需要加载并除法,在第一种情况下,我们必须调用函数。在
我们可以更清楚地看到这一点
^{pr2}$
因为这个值是在编译时预先计算的,所以第二个更快。在And the reason why it is not also optimising away the division is because its behaviour depends on flags, like from __future__ import division and also because of -Q flag./* Cannot fold this operation statically since
the result can depend on the run-time presence
of the -Qnew flag */