Created
February 17, 2025 09:23
-
-
Save BewareMyPower/65b8748941e9b20f228a0cfb9b151891 to your computer and use it in GitHub Desktop.
Run benchmark for stream() vs parallelStream()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package io.bewaremypower; | |
| import java.util.ArrayList; | |
| import java.util.List; | |
| import java.util.Random; | |
| import java.util.concurrent.TimeUnit; | |
| import org.openjdk.jmh.annotations.Benchmark; | |
| import org.openjdk.jmh.annotations.Level; | |
| import org.openjdk.jmh.annotations.Measurement; | |
| import org.openjdk.jmh.annotations.Scope; | |
| import org.openjdk.jmh.annotations.Setup; | |
| import org.openjdk.jmh.annotations.State; | |
| import org.openjdk.jmh.annotations.Warmup; | |
| import org.openjdk.jmh.runner.Runner; | |
| import org.openjdk.jmh.runner.RunnerException; | |
| import org.openjdk.jmh.runner.options.OptionsBuilder; | |
| @State(Scope.Benchmark) | |
| public class StreamBenchmark { | |
| @State(Scope.Benchmark) | |
| public static class Input { | |
| public static final int N = 1000; // TODO: change the N here | |
| public final List<Integer> integers = new ArrayList<>(); | |
| } | |
| @Setup(Level.Trial) | |
| public void setup(Input input) throws Exception { | |
| final var random = new Random(); | |
| input.integers.clear(); | |
| for (int i = 0; i < Input.N; i++) { | |
| input.integers.add(random.nextInt(1000)); | |
| } | |
| } | |
| @Warmup(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS) | |
| @Measurement(iterations = 5, time = 500, timeUnit = TimeUnit.MILLISECONDS) | |
| @Benchmark | |
| public void testStream(Input input) { | |
| final var ignored = input.integers.stream().map(__ -> Integer.toString(__)).toList(); | |
| } | |
| @Warmup(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS) | |
| @Measurement(iterations = 5, time = 500, timeUnit = TimeUnit.MILLISECONDS) | |
| @Benchmark | |
| public void testParallelStream(Input input) { | |
| final var ignored = input.integers.parallelStream().map(__ -> Integer.toString(__)).toList(); | |
| } | |
| public static void main(String[] args) throws RunnerException { | |
| final var opt = | |
| new OptionsBuilder().include(StreamBenchmark.class.getSimpleName()).forks(1).build(); | |
| new Runner(opt).run(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment