JMH:基准测试工具套件-应用


1.背景

多线程性能测试

JMH:简介

JMH is a Java harness for building, running, and analysing nano/micro/milli/macro benchmarks written in Java and other languages targetting the JVM,

由简介可知,JMH不止能对Java语言做基准测试,还能对运行在JVM上的其他语言做基准测试。而且可以分析到纳秒级别。

2.生成maven工程

推荐用法通过命令行创建,构建和运行JMH基准测试。

执行如下命令:

mvn archetype:generate -DinteractiveMode=false -DarchetypeGroupId=org.openjdk.jmh -DarchetypeArtifactId=jmh-java-benchmark-archetype -DgroupId=org.sample -DartifactId=test -Dversion=1.0

特别提醒:命令不要换行

3.启动工程编写测试代码

将生成的代码使用idea打开:

注意截图中已将代码拷贝到了其他地方

 编写一个1+2+3.....+10亿的测试代码

比单线程与多线程的耗时

/*
 * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package org.sample;

import org.openjdk.jmh.annotations.*;

import java.util.concurrent.FutureTask;

/**
 * 编写一个1+2+3.....+10亿的测试代码
 * 

* 比单线程与多线程的耗时 */ @Fork(1) @BenchmarkMode(Mode.AverageTime) @Warmup(iterations = 3) @Measurement(iterations = 5) public class MyBenchmark { // 10亿 static int num = 1000_000_000; /** * 多线程计算 * * @return * @throws Exception */ @Benchmark public int testMethodMore() throws Exception { FutureTask t1 = new FutureTask<>(() -> { int sum = 0; for (int i = 0; i < 250_000_000; i++) { sum += i; } return sum; }); FutureTask t2 = new FutureTask<>(() -> { int sum = 0; for (int i = 250_000_000; i < 500_000_000; i++) { sum += i; } return sum; }); FutureTask t3 = new FutureTask<>(() -> { int sum = 0; for (int i = 500_000_000; i < 750_000_000; i++) { sum += i; } return sum; }); FutureTask t4 = new FutureTask<>(() -> { int sum = 0; for (int i = 750_000_000; i < 1000_000_000; i++) { sum += i; } return sum; }); new Thread(t1).start(); new Thread(t2).start(); new Thread(t3).start(); new Thread(t4).start(); return t1.get() + t2.get() + t3.get() + t4.get(); } /** * 普通循环计算 * * @return * @throws Exception */ @Benchmark public int testMethodSingle() throws Exception { FutureTask t1 = new FutureTask<>(() -> { int sum = 0; for (int i = 0; i <= num; i++) { sum += i; } return sum; }); new Thread(t1).start(); return t1.get(); } }

4.打包与运行

打包:

 运行jar包:

 测试结果:

 可以明显看到多线程比单线程快

提问:如果在单核CPU的情况下测试呢????? 

这个问题很值钱,这设计到你对并发、并行、多线程等核心概念的理解

测试完整日志如下:

F:\JAVAEE高级课程体系\04_高级阶段\java多线程-高级\code\test>java -jar target\benchmarks.jar
# VM invoker: D:\Program Files\Java\jre1.8.0_152\bin\java.exe
# VM options: 
# Warmup: 3 iterations, 1 s each
# Measurement: 5 iterations, 1 s each
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: org.sample.MyBenchmark.testMethodMore

# Run progress: 0.00% complete, ETA 00:00:16
# Fork: 1 of 1
# Warmup Iteration   1: 0.130 s/op
# Warmup Iteration   2: 0.120 s/op
# Warmup Iteration   3: 0.115 s/op
Iteration   1: 0.125 s/op
Iteration   2: 0.118 s/op
Iteration   3: 0.126 s/op
Iteration   4: 0.114 s/op
Iteration   5: 0.122 s/op


Result: 0.121 ±(99.9%) 0.019 s/op [Average]
  Statistics: (min, avg, max) = (0.114, 0.121, 0.126), stdev = 0.005
  Confidence interval (99.9%): [0.102, 0.140]


# VM invoker: D:\Program Files\Java\jre1.8.0_152\bin\java.exe
# VM options: 
# Warmup: 3 iterations, 1 s each
# Measurement: 5 iterations, 1 s each
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: org.sample.MyBenchmark.testMethodSingle

# Run progress: 50.00% complete, ETA 00:00:10
# Fork: 1 of 1
# Warmup Iteration   1: 0.405 s/op
# Warmup Iteration   2: 0.381 s/op
# Warmup Iteration   3: 0.390 s/op
Iteration   1: 0.400 s/op
Iteration   2: 0.385 s/op
Iteration   3: 0.378 s/op
Iteration   4: 0.379 s/op
Iteration   5: 0.388 s/op


Result: 0.386 ±(99.9%) 0.033 s/op [Average]
  Statistics: (min, avg, max) = (0.378, 0.386, 0.400), stdev = 0.009
  Confidence interval (99.9%): [0.353, 0.419]


# Run complete. Total time: 00:00:21

Benchmark                           Mode  Samples  Score  Score error  Units
o.s.MyBenchmark.testMethodMore      avgt        5  0.121        0.019   s/op
o.s.MyBenchmark.testMethodSingle    avgt        5  0.386        0.033   s/op 

完美!