Trying to benchmark Java 8 parallelSetAll() vs setAll()
This question already has an answer here:
Using jmh, I get the following results (size is the length of the array). The score is the runtime per call, in micro seconds (smaller = better).
Benchmark                     (size)  Mode  Cnt       Score       Error  Units
SO34929316.parallelSetAll          1  avgt   20       0.077 ±     0.003  us/op
SO34929316.parallelSetAll       1000  avgt   20       9.935 ±     0.478  us/op
SO34929316.parallelSetAll     100000  avgt   20      56.024 ±     7.008  us/op
SO34929316.parallelSetAll    1000000  avgt   20     518.495 ±    75.331  us/op
SO34929316.parallelSetAll   10000000  avgt   20    5640.574 ±   139.324  us/op
SO34929316.setAll                  1  avgt   20       0.016 ±     0.001  us/op
SO34929316.setAll               1000  avgt   20       1.257 ±     0.023  us/op
SO34929316.setAll             100000  avgt   20     116.760 ±     3.116  us/op
SO34929316.setAll            1000000  avgt   20    1168.868 ±    42.153  us/op
SO34929316.setAll           10000000  avgt   20   12347.399 ±   766.931  us/op
 As you would expect, parallelSetAll is faster for larger arrays and slower for smaller arrays.  However the speedup factor is only ~ x2 according to the test (ran on Win 8.1 / Xeon 2630 v2 / 6 cores (x2)).  
For reference, the code:
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
public class SO34929316 {
  @Param({"1", "1000", "100000", "1000000", "10000000"}) int size;
  long[] array;
  @Setup(Level.Iteration)
  public void setup(){
    array = new long[size];
  }
  @Benchmark
  public void setAll(Blackhole bh) {
    Arrays.setAll(array, n -> n * n * 11 + n * 7);
    bh.consume(array);
  }
  @Benchmark
  public void parallelSetAll(Blackhole bh) {
    Arrays.parallelSetAll(array, n -> n * n * 11 + n * 7);
    bh.consume(array);
  }
}
上一篇: 为什么循环比while循环更快
