public class TestDemo {
int anInt = Integer.MAX_VALUE;
//21亿次+
public void funAdd() {
long i1=System.currentTimeMillis();
int sum=0;
for(int i = 0; i< anInt; i++) {
sum+=i;
}
System.out.println(anInt+"次+:"+(System.currentTimeMillis()-i1));
}
//21十亿次-
public void funSubtract() {
long i1=System.currentTimeMillis();
int sum=0;
for(int i = 0; i< anInt; i++) {
sum-=i;
}
System.out.println(anInt+"次-:"+(System.currentTimeMillis()-i1));
}
//21亿次*
public void funMultiply() {
long i1=System.currentTimeMillis();
int sum=1;
for(int i=0;i<anInt;i++) {
sum*=2;
}
System.out.println(anInt+"次*:"+(System.currentTimeMillis()-i1));
}
//21亿次/
public void funDivide() {
long i1=System.currentTimeMillis();
int sum=Integer.MAX_VALUE;
for(int i=2;i<anInt;i++) {
sum/=2;
}
System.out.println(anInt+"次/:"+(System.currentTimeMillis()-i1));
}
//21亿次<<1 等效*2
public void funMultiplyBit() {
long i1=System.currentTimeMillis();
int sum=1;
for(long i = 0; i< anInt; i++) {
sum= sum << 1;
}
System.out.println(anInt+"次位乘2:"+(System.currentTimeMillis()-i1));
}
//21亿次>>1 等效/2
public void funDivideBit() {
long i1=System.currentTimeMillis();
int sum=Integer.MAX_VALUE;
for(long i = 0; i< anInt; i++) {
sum=sum>>1;
}
System.out.println(anInt+"次位除2:"+(System.currentTimeMillis()-i1));
}
public static void main(String[] args) {
TestDemo demo = new TestDemo();
demo.funAdd();
demo.funSubtract();
demo.funMultiply();
demo.funDivide();
demo.funMultiply();
demo.funDivideBit();
}
}
在运算中,优先使用 【>> 1】 来代替 【/ 2】可大大提升程序性能