Java 数学运算符的相对性能

Java relative performance of math operators

嗨,有人对 Java 数学运算符的相对 performance/cost 有任何参考吗?

最好是代码完成 2 中的东西(我现在手头没有)

它可能看起来像这样:

谢谢。

我拼凑了这个快速、非正式、完全不科学的测试代码:

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

与往常一样,您的里程可能会有所不同。