gpt4 book ai didi

java - junitbenchmark 的动态注释

转载 作者:太空宇宙 更新时间:2023-11-04 06:27:33 24 4
gpt4 key购买 nike

到了我写一些 junitbenchmark 测试的时候了。现在我想从包装类中设置热身和测试轮次。如何从包装器设置 BenchmarkOptions 注释?

我的包装类:

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;

public class Wrapper {

public static void main(String[] args) {
JUnitCore junit = new JUnitCore();
Result result;
result = junit.run(Test.class);
}
}

我在Test.class中的测试方法:

@BenchmarkOptions(benchmarkRounds = 50, warmupRounds = 10)
@Test
public void test1() {
//something to do
}

最佳答案

首先,您的代码不起作用。

  1. 您在测试中缺少 BenchmarkRule
  2. 导入名为 Test 的注释时,不能命名类 Test。这不会编译。

因此我将该类命名为 BenchmarkTest

<小时/>

回到您的问题,您可以使用BenchmarkOptionsSystemProperties。在其'文档中写道

Global settings for benchmarks set through system properties. If IGNORE_ANNOTATION_OPTIONS_PROPERTY is specified, the system properties and defaults will take precedence over the method- and class-level annotations.

这允许您编写如下包装器

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import com.carrotsearch.junitbenchmarks.BenchmarkOptionsSystemProperties;

public class Wrapper {

public static void main(String[] args) {
System.setProperty(BenchmarkOptionsSystemProperties.IGNORE_ANNOTATION_OPTIONS_PROPERTY, "true");
System.setProperty(BenchmarkOptionsSystemProperties.WARMUP_ROUNDS_PROPERTY, "20");
System.setProperty(BenchmarkOptionsSystemProperties.BENCHMARK_ROUNDS_PROPERTY, "20");

JUnitCore junit = new JUnitCore();
Result result = junit.run(BenchmarkTest.class);
}
}

相应的基准看起来像这样

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;

import com.carrotsearch.junitbenchmarks.BenchmarkOptions;
import com.carrotsearch.junitbenchmarks.BenchmarkOptionsSystemProperties;
import com.carrotsearch.junitbenchmarks.BenchmarkRule;

public class BenchmarkTest {

@Rule
public TestRule benchmarkRun = new BenchmarkRule(BenchmarkOptionsSystemProperties.getDefaultConsumers());

@Test
@BenchmarkOptions(benchmarkRounds = 1, warmupRounds = 1)
public void test1() {
int tmp = 1 + 2;
}

}

当您执行 Wrapper 的 mein-method 时,您会得到此输出,您可以在其中看到注释值 1 已被覆盖。

BenchmarkTest.test1: [measured 20 out of 40 rounds, threads: 1 (sequential)] 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

关于java - junitbenchmark 的动态注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26589193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com