Java junitbenchmark的动态注释

Java junitbenchmark的动态注释,java,dynamic,junit,annotations,Java,Dynamic,Junit,Annotations,为了节省时间,我编写了一些junitbenchmark测试。 现在我想从包装器类设置预热和测试回合。 如何从包装器设置BenchmarkOptions注释 我的包装器类: import org.junit.runner.JUnitCore; 导入org.junit.runner.Result; 公共类包装器{ 公共静态void main(字符串[]args){ JUnitCore junit=新的JUnitCore(); 结果; 结果=junit.run(Test.class); } } 我在

为了节省时间,我编写了一些junitbenchmark测试。 现在我想从包装器类设置预热和测试回合。 如何从包装器设置BenchmarkOptions注释

我的包装器类:

import org.junit.runner.JUnitCore;
导入org.junit.runner.Result;
公共类包装器{
公共静态void main(字符串[]args){
JUnitCore junit=新的JUnitCore();
结果;
结果=junit.run(Test.class);
}
}
我在test.class中的测试方法:

@BenchmarkOptions(benchmarkhards=50,warmupRounds=10)
@试验
公共void test1(){
//有事可做
}

首先,您的代码不起作用

  • 测试中缺少
    基准规则
  • 导入名为
    Test
    的注释时,不能命名类
    Test
    。这将无法编译
  • 因此,我将该类命名为
    BenchmarkTest


    回到您的问题,您可以使用
    基准选项SystemProperties
    。在它的文档中

    通过系统属性设置的基准的全局设置。如果指定了IGNORE_ANNOTATION_OPTIONS_属性,则系统属性和默认值将优先于方法级和类级注释

    这允许您按如下方式编写包装器

    import org.junit.runner.JUnitCore;
    导入org.junit.runner.Result;
    导入com.carrotsearch.junitbenchmarks.benchmarkoptions系统属性;
    公共类包装器{
    公共静态void main(字符串[]args){
    System.setProperty(benchmarkoptionsystemproperties.IGNORE_ANNOTATION_OPTIONS_PROPERTY,“true”);
    System.setProperty(基准选项SystemProperties.WARMUP_ROUNDS_PROPERTY,“20”);
    System.setProperty(BenchmarkOptions SystemProperties.BENCHMARK_ROUNDS_PROPERTY,“20”);
    JUnitCore junit=新的JUnitCore();
    结果=junit.run(BenchmarkTest.class);
    }
    }
    
    相应的基准如下所示

    导入org.junit.Rule;
    导入org.junit.Test;
    导入org.junit.rules.TestRule;
    导入com.carrotsearch.junitbenchmarks.BenchmarkOptions;
    导入com.carrotsearch.junitbenchmarks.benchmarkoptions系统属性;
    导入com.carrotsearch.junitbenchmarks.BenchmarkRule;
    公共类基准测试{
    @统治
    public TestRule benchmarkRun=new BenchmarkRule(benchmarkoptionsystemproperties.getDefaultConsumers());
    @试验
    @BenchmarkOptions(benchmarkRounds=1,warmupRounds=1)
    公共void test1(){
    int tmp=1+2;
    }
    }
    
    然后,当您执行包装器的mein方法时,您会得到这个输出,您可以看到注释值1已被覆盖

    BenchmarkTest.test1:[测量了40轮中的20轮,线程:1(顺序)] round:0.00[+-0.00],round.block:0.00[+-0.00],round.gc:0.00[+-0.00],gc.calls:0,gc.time:0.00,time.total:0.01,time.warmup:0.00,time.bench:0.00