java乘法vs^运算符vs数学。整数幂的pow()
我对Java中的功耗计算方式以及可用方法的性能感到好奇。所以我编写了一个简单的测试来检查Math.pow()
、*
和^
操作
public static void main(String[] args) {
int SIZE = 100000000;
int[] arr1 = new int[SIZE];
long st1, end1, st2, end2, st3, end3;
st1 = System.currentTimeMillis();
for (int i = 0; i < SIZE; i++) {
arr1[i] = (int) Math.pow(i, 4);
}
end1 = System.currentTimeMillis();
System.out.println("pow: " + (end1 - st1));
arr1 = new int[SIZE];
st2 = System.currentTimeMillis();
for (int i = 0; i < SIZE; i++) {
arr1[i] = i * i * i * i;
}
end2 = System.currentTimeMillis();
System.out.println("mul: " + (end2 - st2));
arr1 = new int[SIZE];
st3 = System.currentTimeMillis();
for (int i = 0; i < SIZE; i++) {
arr1[i] = i^4;
}
end3 = System.currentTimeMillis();
System.out.println(" ^: " + (end3 - st3));
//to prevent optimizations form skipping the calculations
for (int i = 0; i < SIZE; i++) {
if (arr1[i] == 1){
System.out.println(1);
}
}
System.out.println("done");
}
如果前两个结果是意料之中的:
pow: 19253 19128 19205 19145 19185 19130 19162 19177 19191 19157 | 19173
mul: 91 86 91 85 98 90 90 105 87 95 | 92
^: 80 85 80 70 60 65 75 60 70 60 | 71
第三个有点混乱。为什么^
总是比简单乘法快一点,应该使用哪一种
所有测试都是在类似条件下使用JRE 1.7运行的
# 1 楼答案
^
运算符没有执行求幂运算——它是一个按位“异或”(又名“xor”)使用整数数学将100000000提升到四次方将给出错误的结果——32位整数不能存储那么大的数字
Math.pow()
将使用浮点运算。由于精度问题,答案可能不是100%准确,但应该能够代表所需的结果范围要获得如此大的数字的100%准确值,应该使用
BigInteger
类。然而,它不会特别快。在考虑准确性和性能时,这是一个必须进行的权衡# 2 楼答案
Java中的
^
运算符是位异或,与幂函数不相似参考