How to initialize the data for each invocation in JMH?
Asked Answered
O

1

14

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();
    }
}
Overmatch answered 20/11, 2015 at 8:48 Comment(2)
Have you read JMH Samples, as suggested in docs? Notably, this example answers your question directly: hg.openjdk.java.net/code-tools/jmh/file/bcec9a03787f/…Bailsman
Oh sorry I shouldn't have asked this question when the answer is already in the samples. I admit that I didn't read every code examples. For some reasons, my eyes kept looking at states and fixtures.Overmatch
B
11

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

Brimstone answered 23/11, 2015 at 17:13 Comment(1)
Thank you. I already got the answer from the JMH's author in the comment section. I will mark this as an answer for your effort. I wrote the article about using JMH: medium.com/zappos-engineering/… If you have sometime to review and give me a feedback, I'd appreciate it.Overmatch

© 2022 - 2024 — McMap. All rights reserved.