JMH(Java Microbenchmark Harness)是一个专门用于编写、运行和分析Java微基准测试的工具。它是由OpenJDK项目提供的一个开源项目,旨在帮助开发人员准确地测量和评估Java代码的性能。
JMH提供了一组注解和API,使得编写微基准测试变得简单和方便。使用JMH,您可以定义和运行各种类型的基准测试,包括方法级别的基准测试、类级别的基准测试和多线程基准测试。JMH还提供了丰富的选项和配置,以控制基准测试的执行方式,如迭代次数、线程数、预热时间等。
JMH的主要特点包括:
使用JMH编写和运行基准测试的一般步骤包括:
jmh提供了大量的测试用例,参考资料【1】所示。
@BenchmarkMode(Mode.AverageTime)@OutputTimeUnit(TimeUnit.NANOSECONDS)public class JMHSample_21_ConsumeCPU { /* * At times you require the test to burn some of the cycles doing nothing. * In many cases, you *do* want to burn the cycles instead of waiting. * * For these occasions, we have the infrastructure support. Blackholes * can not only consume the values, but also the time! Run this test * to get familiar with this part of JMH. * * (Note we use static method because most of the use cases are deep * within the testing code, and propagating blackholes is tedious). */ @Benchmark public void consume_0000() { Blackhole.consumeCPU(0); } @Benchmark public void consume_0001() { Blackhole.consumeCPU(1); } @Benchmark public void consume_0002() { Blackhole.consumeCPU(2); } @Benchmark public void consume_0004() { Blackhole.consumeCPU(4); } @Benchmark public void consume_0008() { Blackhole.consumeCPU(8); } @Benchmark public void consume_0016() { Blackhole.consumeCPU(16); } @Benchmark public void consume_0032() { Blackhole.consumeCPU(32); } @Benchmark public void consume_0064() { Blackhole.consumeCPU(64); } @Benchmark public void consume_0128() { Blackhole.consumeCPU(128); } @Benchmark public void consume_0256() { Blackhole.consumeCPU(256); } @Benchmark public void consume_0512() { Blackhole.consumeCPU(512); } @Benchmark public void consume_1024() { Blackhole.consumeCPU(1024); } /* * ============================== HOW TO RUN THIS TEST: ==================================== * * Note the single token is just a few cycles, and the more tokens * you request, then more work is spent (almost linearly) * * You can run this test: * * a) Via the command line: * $ mvn clean install * $ java -jar target/benchmarks.jar JMHSample_21 -f 1 * (we requested single fork; there are also other options, see -h) * * b) Via the Java API: * (see the JMH homepage for possible caveats when running from IDE: * http://openjdk.java/projects/code-tools/jmh/) */ public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(JMHSample_21_ConsumeCPU.class.getSimpleName()) .forks(1) .build(); new Runner(opt).run(); }}
JMH是一个强大的工具,可以帮助开发人员进行准确和可靠的Java微基准测试,以评估和改进代码的性能。它广泛应用于Java开发社区,并被认为是Java性能测试领域的事实标准。
【1】https://github.com/openjdk/jmh/tree/master/jmh-samples/src/main/java/org/openjdk/jmh/samples。
本文链接:http://www.28at.com/showinfo-26-14615-0.htmlOpenJDK JMH——Java程序的基准测试工具
声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com