为什么使用ForkJoin框架进行阶乘计算会降低递归的顺序计算速度

时间:2019-06-10 10:24:17

标签: java factorial fork-join forkjoinpool

我通过两种方式实现阶乘计算-使用递归和使用ForkJoin框架。我原以为ForkJoin的实现会更快,但是在所有尝试测试的情况下,它总是比较慢(我尝试为不同的数字计算阶乘,也试图调整并行度)。这是我的两种实现-没有FJ:

public class SequentialFactorial {

    public static void main(String[] args) {
        long start = System.nanoTime();
        System.out.println(calculateFactorial(BigInteger.valueOf(500)));
        long end = System.nanoTime();
        System.out.println((end - start) + " nanoseconds for sequential");
    }

    private static BigInteger calculateFactorial(BigInteger n) {
        if (n.compareTo(BigInteger.valueOf(2)) <= 0) {
            return n;
        }

        return n.multiply(calculateFactorial(n.subtract(BigInteger.ONE)));
    }
}

并附带:

public class ForkJoinFactorial {

    public static void main( String[] args ) {
        ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
        long start = System.nanoTime();
        System.out.println(forkJoinPool.invoke(new FactorialTask(BigInteger.valueOf(500))));
        long end = System.nanoTime();
        System.out.println((end - start) + " nanoseconds for FJP");
    }
}

public class FactorialTask extends RecursiveTask<BigInteger> {
    private BigInteger number;

    public FactorialTask(BigInteger number) {
        this.number = number;
    }

    @Override
    protected BigInteger compute() {
        if (number.compareTo(BigInteger.valueOf(1)) <= 0) {
            return MathUtil.calculateFactorial(number);
        }
        FactorialTask subtask = new FactorialTask(number.subtract(BigInteger.ONE));
        subtask.fork();
        return number.multiply(subtask.join());
    }
}

在上一次测试中,我得到了这样的结果:

  

5424981纳秒(连续)

     

FJP为11874865纳秒

为什么我的FJ实施速度较慢,我该如何改善呢?

0 个答案:

没有答案