在我的场景中,基准测试中的方法应该在一个线程中顺序运行并按顺序修改状态。
例如,有一个List<Integer>
called num
在基准类中。我想要的是:首先,运行add()
将数字添加到列表中。然后,运行remove()
从列表中删除该号码。
调用顺序必须是add() --> remove()
. If remove()
之前运行add()
或者它们同时运行,它们会引发异常,因为列表中没有元素。
那是,add()
and remove()
必须被称为依次地 and in one thread.
In 使用 JMH 控制方法的顺序 https://stackoverflow.com/questions/36261369/control-the-order-of-methods-using-jmh,我了解到这些方法是按字典顺序运行的。我尝试了下面的代码:
@State(Scope.Group)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.AverageTime)
@Fork(value = 10)
public class ListBenchmark {
private List<Integer> num;
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.verbosity(VerboseMode.NORMAL)
.syncIterations(true)
.threads(1)
.include(".*" + ListBenchmark.class.getCanonicalName() + ".*")
.build();
new Runner(options).run();
}
@Setup(Level.Invocation)
public void setup() throws Exception {
num = new ArrayList<>();
}
@Benchmark
@BenchmarkMode(Mode.SingleShotTime)
@Group("num")
public void add() throws Exception {
num.add(1);
}
@Benchmark
@BenchmarkMode(Mode.SingleShotTime)
@Group("num")
public void remove() throws Exception {
num.remove(0);
}
}
但这不起作用,因为add
方法和remove
方法同时运行。在某些情况下,remove
之前运行add
并提高IndexOutOfBoundsException
.
如何使用 JMH 顺序运行基准测试中的方法?
你从一个错误的前提开始,一切都会因此而失败。您可以看到作者更广泛的解释here https://github.com/openjdk/jmh/blob/master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_15_Asymmetric.java#L56。您希望在隐含不对称的地方实现对称。
如果你想看看需要多少钱add -> remove
将它们放在同一个@Benchmark
,对于个人来说也是如此add
or remove
通过不同的State
。例如:
@State(Scope.Thread)
public static class BothAddAndRemove {
List<Integer> num;
@Setup(Level.Invocation)
public void setup() throws Exception {
num = new ArrayList<>();
}
}
@State(Scope.Thread)
public static class RemoveOnly {
List<Integer> num;
@Setup(Level.Invocation)
public void setup() throws Exception {
num = new ArrayList<>();
num.add(1);
}
}
@Fork(25)
@Benchmark
@BenchmarkMode(Mode.SingleShotTime)
public int add(BothAddAndRemove both) {
both.num.add(1);
return both.num.remove(0);
}
@Fork(25)
@Benchmark
@BenchmarkMode(Mode.SingleShotTime)
public int removeOnly(RemoveOnly removeOnly) {
return removeOnly.num.remove(0);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)