我正在使用JMH而且我找到了一些难以理解的内容:我有一个用$submenus
注释的方法,我设置了@Benchmark
。该方法被调用3次,但在每次迭代调用中,该函数运行的次数相当大且随机。
我的问题是:这个数字是完全随机的吗?有没有办法控制它并确定函数在迭代中运行多少次?设置measurementIterations(3)
的重要性如果每种方式,该函数将随机运行多次?
答案 0 :(得分:5)
measurementIterations
定义了您想要测量基准的测量迭代次数。我不知道你指定了哪些参数,但默认情况下JMH运行基准时间(默认我猜1秒)。这意味着在该时间范围内尽可能频繁地调用基准方法。有可能指定在一次迭代中调用方法的频率( - >批处理)。
我建议研究JMH提供的JMH样本:http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/ 它们是对JMH的一个非常好的介绍,并涵盖了你在基准测试中容易做出的陷阱。
答案 1 :(得分:2)
迭代次数取决于各种JMH模式,我认为您必须使用Avgtime模式,它将执行各种迭代。 ////////////////////////////////////////////////// ///////////////////////////////
Mode.Throughput: Calculate number of operations in a time unit.
Mode.AverageTime: Calculate an average running time.
Mode.SampleTime: Calculate how long does it take for a method to run
(including percentiles).
Mode.SingleShotTime: Just runs a method
once (useful for cold-testing mode).
/////////////////////////////////////////////// /////////////////////////////////
例如使用模式" Mode.SingleShotTime",它将完全按照您在运行中提到的次数执行迭代(见下文)。
//示例跑步者类
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_01_HelloWorld.class.getSimpleName())
.warmupIterations(1)// number of times the warmup iteration should take place
.measurementIterations(1)//number of times the actual iteration should take place
.forks(1)
.shouldDoGC(true)
.build();
new Runner(opt).run();
}
答案 2 :(得分:0)
JMH正在进行热身迭代,这些迭代未经测量但对于有效结果是必需的。
measurementIterations
定义应测量的迭代次数。这不包括预热,因为没有测量预热。
答案 3 :(得分:-1)
是的,在每次迭代中,方法运行的时间都是随机的(这是该方法可以运行的最大次数)。时代并不重要。重要的是每次使用的平均时间。
此外,您可以控制使用measurementIterations()
运行多少次迭代,以及使用measurementTime()
控制每次迭代的持续时间。
例如,如果您要仅使用1次迭代来运行方法,并且方法的持续时间为1ms,而没有预热,则只需将warmupIterations设置为0,measurementTime设置为1ms,measurementIterations设置为1。如下所示:
Options opt = new OptionsBuilder()
.include(xxx.class.getSimpleName())
.warmupIterations(0)
.measurementTime(TimeValue.milliseconds(1))
.measurementIterations(1)
.forks(1)
.build();
多重迭代的意义:运行更多,结果应该更可靠。