我正在对一些代码进行基准测试,但即使使用完全相同的算法,我也无法像使用java.math.BigInteger
那样运行得快。因此,我将java.math.BigInteger
源代码复制到我的程序包中,并尝试了以下操作:
//import java.math.BigInteger;
public class MultiplyTest {
public static void main(String[] args) {
Random r = new Random(1);
long tm = 0, count = 0,result=0;
for (int i = 0; i < 400000; i++) {
int s1 = 400, s2 = 400;
BigInteger a = new BigInteger(s1 * 8, r), b = new BigInteger(s2 * 8, r);
long tm1 = System.nanoTime();
BigInteger c = a.multiply(b);
if (i > 100000) {
tm += System.nanoTime() - tm1;
count++;
}
result+=c.bitLength();
}
System.out.println((tm / count) + "nsec/mul");
System.out.println(result);
}
}
当我在MacOS上运行此代码(jdk 1.8.0_144-b01),它会输出:12089nsec/mul
2559044166
当我取消注释import语句并运行它时:
4098nsec/mul
2559044166
如果使用JDK版本的BigInteger,即使使用完全相同的代码,速度也比使用我的版本快近三倍。
我已经使用javap检查了字节码,并比较了在使用选项运行时的编译器输出。
-Xbatch -XX:-TieredCompilation -XX:+PrintCompilation -XX:+UnlockDiagnosticVMOptions
-XX:+PrintInlining -XX:CICompilerCount=1
两个版本似乎都生成了相同的代码。那么,热点是否使用了我不能在我的代码中使用的某些预计算优化?我一直以为它们不会这样做。是什么解释了这种差异呢?