Using JMH to benchmark Java 8 Stream API ( parellel vs sequential) to sum up integer in list
Ming Qin
mingqin1 at yahoo.com
Fri Dec 12 05:33:33 UTC 2014
Hi: I wrote a blog ( http://wp.me/p1FzYe-9k ) to use JMH 1.3.3 to benchmark throughput of summing up integers hosted in a List object through different Java 8 API ( array, iterator , Stream sequential and Stream Parallel) .The result of my JMH benachmark codes indicated that Stream Parallel was the slowest one to sum up all integers . I run this command to get results -java -jar target/benchmarks.jar JMHSample_01 -wi 5 -t 1 -i 5 -f 1
Before seeing the results, I anticipated that Steam Parallel approach should get better throughput number that Stream Sequential.
I doubted that the method of parallelSumIntegers() was not implemented correctly .
Below are my codes.
import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.concurrent.TimeUnit;import org.openjdk.jmh.annotations.Benchmark;import org.openjdk.jmh.annotations.BenchmarkMode;import org.openjdk.jmh.annotations.Mode;import org.openjdk.jmh.annotations.OutputTimeUnit;import org.openjdk.jmh.annotations.Scope;import org.openjdk.jmh.annotations.Setup;import org.openjdk.jmh.annotations.State;import org.openjdk.jmh.runner.Runner;import org.openjdk.jmh.runner.RunnerException;import org.openjdk.jmh.runner.options.Options;import org.openjdk.jmh.runner.options.OptionsBuilder; @State(Scope.Benchmark)public class JMHSample_01_HelloWorld {volatile int counts = 9999999;volatile List<Integer> values = new ArrayList<>(counts);volatile int processors = Runtime.getRuntime().availableProcessors(); @Setuppublic void setup() {populate(values);} public void populate ( List<Integer> list){for ( int i=0; i<counts ; i++){if ( i < counts/2){list.add(i, i );}else {list.add (i, i-counts);}} } @Benchmark at BenchmarkMode(Mode.Throughput)@OutputTimeUnit(TimeUnit.SECONDS)public int iteratorSumIntegers(){int result =0;Iterator ite = values.iterator();while ( ite.hasNext()){result += (int)ite.next();} return result;} @Benchmark at BenchmarkMode(Mode.Throughput)@OutputTimeUnit(TimeUnit.SECONDS)public int fooEachSumIntegers(){int result =0;for (Integer value :values) {result += value.intValue();}return result;} @Benchmark at BenchmarkMode(Mode.Throughput)@OutputTimeUnit(TimeUnit.SECONDS)public int parallelSumIntegers( ){int result = values.parallelStream().mapToInt(i->i).sum(); return result; } @Benchmark at BenchmarkMode(Mode.Throughput)@OutputTimeUnit(TimeUnit.SECONDS)public int sequentialSumIntegers( ){int result = values.stream().mapToInt(i->i).sum(); return result; } public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder().include(JMHSample_01_HelloWorld.class.getSimpleName()).forks(1).build(); new Runner(opt).run();} }
More information about the jmh-dev
mailing list