您是否有人对Java数学运算符的相对性能/成本有任何参考?
理想情况下就像Code Complete 2中的那样(我现在手头上还没有)
它可能看起来像这样:
感谢。
答案 0 :(得分:1)
我把这个快速,非正式,完全不科学的测试代码鞭打在一起:
import java.util.function.BinaryOperator;
public class Test {
private static void test(String desc, BinaryOperator<Double> op, double a, double b, long startIter)
{
long maxIter = startIter;
long elapsed;
do {
maxIter *= 2;
long start = System.currentTimeMillis();
for (long niter = 0; niter < maxIter; ++niter) {
double res = op.apply(a, b);
}
elapsed = System.currentTimeMillis() - start;
} while (elapsed <= 10_000);
System.out.printf("%-15s/sec\t%g\n",
desc, (maxIter * 1000.0) / elapsed);
}
public static void main(String[] arg)
{
test("Addition (double)", (Double a, Double b) -> {
return a + b;
}, 483902.7743, 42347.775, 10_000_000);
test("Subtraction (double)", (Double a, Double b) -> {
return a - b;
}, 483902.7743, 42347.775, 10_000_000);
test("Multiplication (double)", (Double a, Double b) -> {
return a * b;
}, 483902.7743, 42347.775, 1_000_000);
test("Division (double)", (Double a, Double b) -> {
return a / b;
}, 483902.7743, 42347.775, 1_000_000);
test("Log10", (Double a, Double b) -> {
return Math.log10(a);
}, 483902.7743, 42347.775, 1_000_000);
test("LogE", (Double a, Double b) -> {
return Math.log(a);
}, 483902.7743, 42347.775, 1_000_000);
test("Power", (Double a, Double b) -> {
return Math.pow(a, b);
}, 483902.7743, 12, 100_000);
}
}
在我的环境中---标准Java 8 JDK,Intel Core2 Quad Q8300 @ 2.5GHz ---此测试的代表性原始输出是:
Addition (double)/sec 6.18619e+08
Subtraction (double)/sec 4.10651e+08
Multiplication (double)/sec 3.27010e+07
Division (double)/sec 3.22215e+07
Log10 /sec 1.99330e+07
LogE /sec 1.99206e+07
Power /sec 8.67870e+06
转换为相对表现我们有:
Addition 1.0
Subtraction 1.5
Multiplication 18.9
Division 19.2
Log10 31.0
LogE 31.1
Power 71.3
像往常一样,您的里程可能会有所不同。