Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize the data for each invocation in JMH?

Tags:

java

jmh

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();
    }
}
like image 672
hussachai Avatar asked Nov 20 '15 08:11

hussachai


People also ask

How do I set up JMH?

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.

How do you run a JMH benchmark?

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.

What is JMH operation?

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.

What is JMH in Java?

JMH is a Java harness for building, running, and analysing nano/micro/milli/macro benchmarks written in Java and other languages targeting the JVM.


1 Answers

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

like image 75
ytrewq Avatar answered Oct 06 '22 11:10

ytrewq