我正在对一些代码进行基准测试,但我无法让它运行得像java.math.BigInteger https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html,即使使用完全相同的算法。
所以我复制了java.math.BigInteger https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html源到我自己的包并尝试了这个:
//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
当我在导入行未注释的情况下运行它时:
4098nsec/mul
2559044166
使用 JDK 版本的 BigInteger 时,速度几乎是我的版本的三倍,即使它使用完全相同的代码。
我使用 javap 检查了字节码,并比较了使用选项运行时的编译器输出:
-Xbatch -XX:-TieredCompilation -XX:+PrintCompilation -XX:+UnlockDiagnosticVMOptions
-XX:+PrintInlining -XX:CICompilerCount=1
并且两个版本似乎生成相同的代码。
那么热点是否使用了一些我无法在代码中使用的预先计算的优化?我一直明白他们没有。
如何解释这种差异?