Cannot run OptimisationExampleFixed
zhugw opened this issue · comments
zhugw commented
Hi,
Recently I'm reading this book, and now encountered some problems. When I run com.insightfullogic.java8.answers.chapter6.OptimisationExampleFixed
, it hint
No matching benchmarks. Miss-spelled regexp?
Use EXTRA verbose mode to debug the pattern matching.
What's wrong? how to solve it?
Switch commented
@zhugw
Recently,I get the same questions. I think that the jmh version is too old.
I use IDEA and JMH plugin.
This is my solution.
- use release version
I use 1.19.
This is dependecy
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
</dependency>
-
use annotation
@Benchmark
-
write a main method
-
run it
after refactor
package com.insightfullogic.java8.examples.chapter6;
import org.openjdk.jmh.annotations.*;
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;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.IntFunction;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.summingDouble;
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
public class DiceRolls {
private static final int N = 100000000;
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.forks(1)
.include(DiceRolls.class.getSimpleName())
.build();
new Runner(options).run();
}
@Benchmark
public Map<Integer, Double> serialDiceRolls() {
double fraction = 1.0 / N;
return IntStream.range(0, N)
.mapToObj(twoDiceThrows())
.collect(groupingBy(side -> side, summingDouble(n -> fraction)));
}
@Benchmark
public Map<Integer, Double> parallelDiceRolls() {
double fraction = 1.0 / N;
return IntStream.range(0, N)
.parallel()
.mapToObj(twoDiceThrows())
.collect(groupingBy(side -> side, summingDouble(n -> fraction)));
}
private static IntFunction<Integer> twoDiceThrows() {
return i -> {
ThreadLocalRandom random = ThreadLocalRandom.current();
int firstThrow = random.nextInt(1, 7);
int secondThrow = random.nextInt(1, 7);
return firstThrow + secondThrow;
};
}
}
Richard Warburton commented
Indeed - the JMH version used was current when the book was published. I don't plan to commit to updating the example code for every JMH release until the end of time so I figure its best to leave it at the original version. I hope this clarifies things.