我正在使用LongStream
的rangeClosed
测试数字和的性能。当我通过JMH测试性能时,结果如下。
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Fork(value = 1, jvmArgs = {"-Xms4G", "-Xmx4G"})
@State(Scope.Benchmark)
@Warmup(iterations = 10, time = 10)
@Measurement(iterations = 10, time = 10)
public class ParallelStreamBenchmark {
private static final long N = 10000000L;
@Benchmark
public long sequentialSum() {
return Stream.iterate(1L, i -> i + 1).limit(N).reduce(0L, Long::sum);
}
@Benchmark
public long parallelSum() {
return Stream.iterate(1L, i -> i + 1).limit(N).parallel().reduce(0L, Long::sum);
}
@Benchmark
public long rangedReduceSum() {
return LongStream.rangeClosed(1, N).reduce(0, Long::sum);
}
@Benchmark
public long rangedSum() {
return LongStream.rangeClosed(1, N).sum();
}
@Benchmark
public long parallelRangedReduceSum() {
return LongStream.rangeClosed(1, N).parallel().reduce(0L, Long::sum);
}
@Benchmark
public long parallelRangedSum() {
return LongStream.rangeClosed(1, N).parallel().sum();
}
@TearDown(Level.Invocation)
public void tearDown() {
System.gc();
}
Benchmark Mode Cnt Score Error Units
ParallelStreamBenchmark.parallelRangedReduceSum avgt 10 7.895 ± 0.450 ms/op
ParallelStreamBenchmark.parallelRangedSum avgt 10 1.124 ± 0.165 ms/op
ParallelStreamBenchmark.rangedReduceSum avgt 10 6.832 ± 0.165 ms/op
ParallelStreamBenchmark.rangedSum avgt 10 21.564 ± 0.831 ms/op
rangedReduceSum
和rangedSum
之间的区别在于,仅使用内部函数sum()。为什么会有这么多的性能差异?
[确认sum()
函数最终使用reduce(0, Long::sum)
后,是否与在reduce(0, Long::sum)
方法中使用rangedReduceSum
相同?
我完成了与OP相同的任务,并且可以再现完全相同的结果:第二个任务要慢大约3倍。但是,当我将预热更改为仅1次迭代时,事情开始变得有趣起来:
# Benchmark: test.ParallelStreamBenchmark.rangedReduceSum
# Warmup Iteration 1: 3.619 ms/op
Iteration 1: 3.931 ms/op
Iteration 2: 3.927 ms/op
Iteration 3: 3.834 ms/op
Iteration 4: 4.006 ms/op
Iteration 5: 4.605 ms/op
Iteration 6: 6.454 ms/op
Iteration 7: 6.466 ms/op
Iteration 8: 6.328 ms/op
Iteration 9: 6.370 ms/op
Iteration 10: 6.244 ms/op
# Benchmark: test.ParallelStreamBenchmark.rangedSum
# Warmup Iteration 1: 3.971 ms/op
Iteration 1: 4.034 ms/op
Iteration 2: 3.970 ms/op
Iteration 3: 3.957 ms/op
Iteration 4: 4.024 ms/op
Iteration 5: 4.278 ms/op
Iteration 6: 19.302 ms/op
Iteration 7: 19.132 ms/op
Iteration 8: 19.189 ms/op
Iteration 9: 18.842 ms/op
Iteration 10: 18.292 ms/op
Benchmark Mode Cnt Score Error Units
ParallelStreamBenchmark.rangedReduceSum avgt 10 5.216 ± 1.871 ms/op
ParallelStreamBenchmark.rangedSum avgt 10 11.502 ± 11.879 ms/op
第5次迭代后,每个任务都会明显减慢速度。对于第二项任务,它在第5次迭代后精确地减速了3倍。如果我们将预热算作迭代,那么经过10次迭代,就已经很慢地开始了。看起来像是Benchmark库中的错误,无法与GC配合使用。但是,正如警告所言,在这种情况下的基准测试结果仅供参考。