jmh 的使用

新建 Module

项目名右键 -> New -> Module:
jmh 的使用_第1张图片
这里选择 webapp:
jmh 的使用_第2张图片
然后给这个 Module 起一个名字:
jmh 的使用_第3张图片
目录结构:
jmh 的使用_第4张图片

代码

package org.example;

import org.openjdk.jmh.annotations.*;

import java.util.Arrays;
import java.util.concurrent.FutureTask;

@Fork(1)
//多次测试取平均
@BenchmarkMode(Mode.AverageTime)
// 程序预热
@Warmup(iterations = 3)
//5轮测试取平均
@Measurement(iterations = 5)
public class MyBenchmark {
    // 长度为 1 亿的数组
    static int[] ARRAY = new int[1000_000_00];
    static {
        Arrays.fill(ARRAY, 1);
    }

    @Benchmark
    public int multiThreads() throws Exception{
        int [] array = ARRAY;
        // 创建 4 个 FutureTask
        FutureTask<Integer> task1 = new FutureTask<>(() -> {
            int sum = 0;
            for (int i = 0; i < 250_000_00; i++) {
                sum += array[0 + i];
            }
            return sum;
        });
        FutureTask<Integer> task2 = new FutureTask<>(() -> {
            int sum = 0;
            for (int i = 0; i < 250_000_00; i++) {
                sum += array[250_000_00 + i];
            }
            return sum;
        });
        FutureTask<Integer> task3 = new FutureTask<>(() -> {
            int sum = 0;
            for (int i = 0; i < 250_000_00; i++) {
                sum += array[500_000_00 + i];
            }
            return sum;
        });
        FutureTask<Integer> task4 = new FutureTask<>(() -> {
            int sum = 0;
            for (int i = 0; i < 250_000_00; i++) {
                sum += array[750_000_00 + i];
            }
            return sum;
        });
        // 启动 4 个线程
        new Thread(task1).start();
        new Thread(task2).start();
        new Thread(task3).start();
        new Thread(task4).start();
        // 通过 FutureTask 获得返回值
        return task1.get() + task2.get() + task3.get() + task4.get();
    }

    @Benchmark
    public int singleThread() throws Exception{
        int [] array = ARRAY;
        // 创建一个 FutureTask
        FutureTask<Integer> task = new FutureTask<>(() -> {
            int sum = 0;
            for (int i = 0; i < 1000_000_00; i++) {
                sum += array[i];
            }
            return sum;
        });
        // 启动线程,单线程完成累加和任务
        new Thread(task).start();
        // 通过 FutureTask 获得返回值
        return task.get();
    }

    public static void main(String[] args) {

    }
}

pom.xml

注意:pom.xml 文件是重点,如果 pom.xml 有问题,可能导致无法成功打正确的 .jar 包。如果自己尝试无法正确打包,建议完全粘贴以下的 pom.xml。


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>daily_demoartifactId>
        <groupId>org.examplegroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>
    <artifactId>jmh_testartifactId>
    <packaging>jarpackaging>
    <version>1.0-SNAPSHOTversion>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <javac.target>1.8javac.target>
        <uberjar.name>benchmarksuberjar.name>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.10version>
        dependency>
        <dependency>
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-classicartifactId>
            <version>1.2.3version>
        dependency>
        <dependency>
            <groupId>org.openjdk.jmhgroupId>
            <artifactId>jmh-coreartifactId>
            <version>1.0version>
        dependency>
        <dependency>
            <groupId>org.openjdk.jmhgroupId>
            <artifactId>jmh-generator-annprocessartifactId>
            <version>1.0version>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.1version>
                <configuration>
                    <compilerVersion>${javac.target}compilerVersion>
                    <source>${javac.target}source>
                    <target>${javac.target}target>
                configuration>
            plugin>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-shade-pluginartifactId>
                <version>2.2version>
                <executions>
                    <execution>
                        <phase>packagephase>
                        <goals>
                            <goal>shadegoal>
                        goals>
                        <configuration>
                            <finalName>${uberjar.name}finalName>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>org.openjdk.jmh.MainmainClass>
                                transformer>
                            transformers>
                            <filters>
                                <filter>
                                    
                                    <artifact>*:*artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SFexclude>
                                        <exclude>META-INF/*.DSAexclude>
                                        <exclude>META-INF/*.RSAexclude>
                                    excludes>
                                filter>
                            filters>
                        configuration>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

打 jar 包

点击 IDEA 右侧的 Maven,先点击 clean,然后点 package
jmh 的使用_第5张图片
然后即可看到打好的 jar 包:
jmh 的使用_第6张图片

benmarch 测试

然后点击下方的 Terminal,运行如下命令:

(base) PS D:\IdeaProjects\daily_demo> cd jmh_test\target   
(base) PS D:\IdeaProjects\daily_demo\jmh_test\target> java -jar .\benchmarks.jar

jmh 的使用_第7张图片

运行结果:

# VM invoker: C:\Program Files\Java\jre1.8.0_291\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.example.MyBenchmark.multiThreads

# Run progress: 0.00% complete, ETA 00:00:16
# Fork: 1 of 1
# Warmup Iteration   1: 0.017 s/op
# Warmup Iteration   2: 0.018 s/op
# Warmup Iteration   3: 0.016 s/op
Iteration   1: 0.019 s/op
Iteration   2: 0.018 s/op
Iteration   3: 0.020 s/op
Iteration   4: 0.020 s/op
Iteration   5: 0.020 s/op


Result: 0.019 ±(99.9%) 0.005 s/op [Average]
  Statistics: (min, avg, max) = (0.018, 0.019, 0.020), stdev = 0.001
  Confidence interval (99.9%): [0.015, 0.024]


# VM invoker: C:\Program Files\Java\jre1.8.0_291\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.example.MyBenchmark.singleThread

# Run progress: 50.00% complete, ETA 00:00:10
# Fork: 1 of 1
# Warmup Iteration   1: 0.042 s/op
# Warmup Iteration   2: 0.040 s/op
# Warmup Iteration   3: 0.039 s/op
Iteration   1: 0.040 s/op
Iteration   2: 0.042 s/op
Iteration   3: 0.042 s/op
Iteration   4: 0.041 s/op
Iteration   5: 0.044 s/op


Result: 0.042 ±(99.9%) 0.006 s/op [Average]
  Statistics: (min, avg, max) = (0.040, 0.042, 0.044), stdev = 0.001
  Confidence interval (99.9%): [0.036, 0.048]


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

Benchmark                       Mode  Samples  Score  Score error  Units
o.e.MyBenchmark.multiThreads    avgt        5  0.019        0.005   s/op
o.e.MyBenchmark.singleThread    avgt        5  0.042        0.006   s/op

你可能感兴趣的:(java)