java multiplication and division of numeric type bit operation principle of optimality

Bitwise operators, the << and >> operators a bit pattern to the left or right, the use of this operator will be sometimes very fast operation. << represents the left by 2, represents the right to remove 2 >>

  • int a = 256 * 100; then on a 256 to 100 are added.
  • For bit operation principle is, + 100 = 64 + 32 = 2. 4. 6 ^ + ^ 2 + 2 ^ 2. 5
    A = 256 * (2 ^. 6 + 2 + 2 ^ 2 ^. 5) * 2 = 256. 6 ^ + 256 + 256 * 5 * 2 ^ 2 ^ 2
    = (256 << 6) + (<< 5 256) + (256 << 2)
    behind with << operator how many times a power of 2

Light might say there is no particular sense, we use the code to test.

public class Test {

 	public static void test1(){
       double start  = System.currentTimeMillis();
       int a = 0;
       for(int i = 0;i<50000;i++) {
           a += 256 * 100;
       }
       System.out.println(a);
       double end = System.currentTimeMillis();
       System.out.println("运行时间: " + (end - start));
   }

   public static void test2(){
       double start  = System.currentTimeMillis();
       int b = 0;
       for(int i = 0;i<50000;i++) {
           b += (256 << 6) + (256 << 5) + (256 << 2);
       }
       System.out.println(b);
       double end = System.currentTimeMillis();
       System.out.println("运行时间: " + (end - start));
   }



   public static void main(String[] args) {
       // TODO Auto-generated method stub
       test1();
       test2();
   }

}

We can obtain the following results:
Here Insert Picture Description


Summary:
The actual procedure when we calculate, if the calculation is performed only once, multiplication, and bitwise operation time is in milliseconds, little difference between the time a part is consumed in the output statements and so on. When the calculation is performed plural times, java program optimization calculation, and the calculation time by multiplying the number of two bits or less operator, but actually takes a long time to be multiplied, it can be seen from the results, the number of cycles increases, the time required for calculation bitwise less time than multiplication.

Guess you like

Origin blog.csdn.net/fight252/article/details/90747162