Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is integer divisions not optimised when compiling to bytecode?

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
like image 706
satoru Avatar asked Mar 20 '23 21:03

satoru


1 Answers

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

like image 106
thefourtheye Avatar answered Apr 26 '23 05:04

thefourtheye