I'm trying to create the benchmark that modifies the collection. The problem is that I don't know how to initialize data for each invocation.
Assume that Test.DATA is a collection that contains 200 elements.
The test
method removes data based on a.isTrue()
's value.
I know that @Setup
is similar to JUnit's @Setup
. I want to use @Before
but I couldn't find one in JMH.
How can I initialize the data each time before the test
method is invoked?
Thank you very much in advance.
@State(Scope.Thread)
public class JavaCollectionBenchmark {
List<Foo> cols;
@Setup
public void prepare(){
cols= new ArrayList<>(Test.DATA);
}
@Benchmark
public long test(){
if(cols.size() != 200) {
System.out.println("SECOND TIME DOESN'T WORK!");
System.exit(0);
}else{
System.out.println("FIRST TIME");
}
cols.removeIf(a-> a.isTrue());
return cols.size();
}
}
The easiest way to get started with JMH is to generate a new JMH project using the JMH Maven archetype. The JMH Maven archetype will generate a new Java project with a single, example benchmark Java class, and a Maven pom. xml file. The Maven pom.
There are two ways to run the JMH benchmark, uses Maven or run it via a JMH Runner class directly. 3.1 Maven, package it as a JAR and run it via org. openjdk.
In JMH, "operation" is an abstract unit of work. See e.g. the sample result: Benchmark Mode Cnt Score Error Units MyBenchmark.testMethod avgt 5 5.068 ± 0.586 ns/op. Here, the performance is 5.068 nanoseconds per operation. Nominally, one operation is one @Benchmark invocation.
JMH is a Java harness for building, running, and analysing nano/micro/milli/macro benchmarks written in Java and other languages targeting the JVM.
Check Level
parameter on @Setup
annotation. The equivalent of @Before
is
@Setup(Level.Invocation)
which is explained, together with many warnings (WARNING: HERE BE DRAGONS! THIS IS A SHARP TOOL.
, etc.) here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With