Tuesday, 2 August 2022

JMH: Benchmarking modes

At the time of writing this post, JMH support 4 benchmarking modes.

 

a. Throughput: operations per unit of time. It Measures the raw throughput by continuously calling the benchmark method in a time-bound iteration, and counting how many times we executed the method.

 

b. AverageTime: average time per  operation. It measures the average execution time, and it does it in the way similar to Mode.Throughput.

 

c. SampleTime: samples the time for each operation. With this mode, we are still running the method in a time-bound iteration, but instead of measuring the total time, we measure the time spent in some of the benchmark method calls.

 

d. SingleShotTime: measures the time for a single operation. measures the single method invocation time. We do only the single benchmark method invocation. The iteration time is meaningless in this mode: as soon as benchmark method stops, the iteration is over.

 


How to enable Throughput mode?

Annotate the method with ‘@BenchmarkMode(Mode.Throughput)’.

 

Example

@Benchmark
@BenchmarkMode(Mode.Throughput)
public void measureThroughput() throws InterruptedException {
    TimeUnit.MILLISECONDS.sleep(100);
}

 

How to enable AverageTime mode?

@Benchmark
@BenchmarkMode(Mode.AverageTime)
public void measureAverageTime() {
    sleepNMilliSeconds(100);
}

 

How to enable SampleTime mode?

@Benchmark
@BenchmarkMode(Mode.SampleTime)
public void measureSampleTime() {
    sleepNMilliSeconds(100);
}

How to enable SingleShotTime mode?

@Benchmark
@BenchmarkMode(Mode.SingleShotTime)
public void measureSingleShotTime() {
    sleepNMilliSeconds(100);
}

Find the below working application.

 

BenchmarkingModes.java

package com.sample.app;

import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

public class BenchmarkingModes {

    private void sleepNMilliSeconds(int n) {
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    public void measureThroughput() {
        sleepNMilliSeconds(50);
    }

    @Benchmark
    @BenchmarkMode(Mode.AverageTime)
    public void measureAverageTime() {
        sleepNMilliSeconds(50);
    }

    @Benchmark
    @BenchmarkMode(Mode.SampleTime)
    public void measureSampleTime() {
        sleepNMilliSeconds(50);
    }

    @Benchmark
    @BenchmarkMode(Mode.SingleShotTime)
    public void measureSingleShotTime() {
        sleepNMilliSeconds(50);
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(BenchmarkingModes.class.getSimpleName())
                .forks(1)
                .measurementIterations(4)
                .warmupIterations(3)
                .build();

        new Runner(opt).run();
    }
}

Output

# JMH version: 1.35
# VM version: JDK 15.0.2, Java HotSpot(TM) 64-Bit Server VM, 15.0.2+7-27
# VM invoker: /Library/Java/JavaVirtualMachines/jdk-15.0.2.jdk/Contents/Home/bin/java
# VM options: -Dfile.encoding=UTF-8 -XX:+ShowCodeDetailsInExceptionMessages
# Blackhole mode: full + dont-inline hint (auto-detected, use -Djmh.blackhole.autoDetect=false to disable)
# Warmup: 3 iterations, 10 s each
# Measurement: 4 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Throughput, ops/time
# Benchmark: com.sample.app.BenchmarkingModes.measureThroughput

# Run progress: 0.00% complete, ETA 00:03:30
# Fork: 1 of 1
# Warmup Iteration   1: 18.887 ops/s
# Warmup Iteration   2: 19.020 ops/s
# Warmup Iteration   3: 18.874 ops/s
Iteration   1: 18.848 ops/s
Iteration   2: 18.795 ops/s
Iteration   3: 18.930 ops/s
Iteration   4: 18.932 ops/s


Result "com.sample.app.BenchmarkingModes.measureThroughput":
  18.876 ±(99.9%) 0.433 ops/s [Average]
  (min, avg, max) = (18.795, 18.876, 18.932), stdev = 0.067
  CI (99.9%): [18.443, 19.310] (assumes normal distribution)


# JMH version: 1.35
# VM version: JDK 15.0.2, Java HotSpot(TM) 64-Bit Server VM, 15.0.2+7-27
# VM invoker: /Library/Java/JavaVirtualMachines/jdk-15.0.2.jdk/Contents/Home/bin/java
# VM options: -Dfile.encoding=UTF-8 -XX:+ShowCodeDetailsInExceptionMessages
# Blackhole mode: full + dont-inline hint (auto-detected, use -Djmh.blackhole.autoDetect=false to disable)
# Warmup: 3 iterations, 10 s each
# Measurement: 4 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: com.sample.app.BenchmarkingModes.measureAverageTime

# Run progress: 33.33% complete, ETA 00:02:20
# Fork: 1 of 1
# Warmup Iteration   1: 0.053 s/op
# Warmup Iteration   2: 0.053 s/op
# Warmup Iteration   3: 0.053 s/op
Iteration   1: 0.053 s/op
Iteration   2: 0.053 s/op
Iteration   3: 0.052 s/op
Iteration   4: 0.053 s/op


Result "com.sample.app.BenchmarkingModes.measureAverageTime":
  0.053 ±(99.9%) 0.001 s/op [Average]
  (min, avg, max) = (0.052, 0.053, 0.053), stdev = 0.001
  CI (99.9%): [0.051, 0.054] (assumes normal distribution)


# JMH version: 1.35
# VM version: JDK 15.0.2, Java HotSpot(TM) 64-Bit Server VM, 15.0.2+7-27
# VM invoker: /Library/Java/JavaVirtualMachines/jdk-15.0.2.jdk/Contents/Home/bin/java
# VM options: -Dfile.encoding=UTF-8 -XX:+ShowCodeDetailsInExceptionMessages
# Blackhole mode: full + dont-inline hint (auto-detected, use -Djmh.blackhole.autoDetect=false to disable)
# Warmup: 3 iterations, 10 s each
# Measurement: 4 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Sampling time
# Benchmark: com.sample.app.BenchmarkingModes.measureSampleTime

# Run progress: 66.66% complete, ETA 00:01:10
# Fork: 1 of 1
# Warmup Iteration   1: 0.053 ±(99.9%) 0.001 s/op
# Warmup Iteration   2: 0.053 ±(99.9%) 0.001 s/op
# Warmup Iteration   3: 0.053 ±(99.9%) 0.001 s/op
Iteration   1: 0.053 ±(99.9%) 0.001 s/op
                 measureSampleTime·p0.00:   0.050 s/op
                 measureSampleTime·p0.50:   0.054 s/op
                 measureSampleTime·p0.90:   0.055 s/op
                 measureSampleTime·p0.95:   0.055 s/op
                 measureSampleTime·p0.99:   0.055 s/op
                 measureSampleTime·p0.999:  0.055 s/op
                 measureSampleTime·p0.9999: 0.055 s/op
                 measureSampleTime·p1.00:   0.055 s/op

Iteration   2: 0.053 ±(99.9%) 0.001 s/op
                 measureSampleTime·p0.00:   0.050 s/op
                 measureSampleTime·p0.50:   0.054 s/op
                 measureSampleTime·p0.90:   0.055 s/op
                 measureSampleTime·p0.95:   0.055 s/op
                 measureSampleTime·p0.99:   0.055 s/op
                 measureSampleTime·p0.999:  0.055 s/op
                 measureSampleTime·p0.9999: 0.055 s/op
                 measureSampleTime·p1.00:   0.055 s/op

Iteration   3: 0.053 ±(99.9%) 0.001 s/op
                 measureSampleTime·p0.00:   0.050 s/op
                 measureSampleTime·p0.50:   0.053 s/op
                 measureSampleTime·p0.90:   0.055 s/op
                 measureSampleTime·p0.95:   0.055 s/op
                 measureSampleTime·p0.99:   0.055 s/op
                 measureSampleTime·p0.999:  0.055 s/op
                 measureSampleTime·p0.9999: 0.055 s/op
                 measureSampleTime·p1.00:   0.055 s/op

Iteration   4: 0.053 ±(99.9%) 0.001 s/op
                 measureSampleTime·p0.00:   0.050 s/op
                 measureSampleTime·p0.50:   0.053 s/op
                 measureSampleTime·p0.90:   0.055 s/op
                 measureSampleTime·p0.95:   0.055 s/op
                 measureSampleTime·p0.99:   0.055 s/op
                 measureSampleTime·p0.999:  0.055 s/op
                 measureSampleTime·p0.9999: 0.055 s/op
                 measureSampleTime·p1.00:   0.055 s/op



Result "com.sample.app.BenchmarkingModes.measureSampleTime":
  N = 755
  mean =      0.053 ±(99.9%) 0.001 s/op

  Histogram, s/op:
    [0.050, 0.051) = 72 
    [0.051, 0.051) = 59 
    [0.051, 0.052) = 47 
    [0.052, 0.052) = 51 
    [0.052, 0.053) = 28 
    [0.053, 0.053) = 47 
    [0.053, 0.054) = 67 
    [0.054, 0.054) = 68 
    [0.054, 0.055) = 123 
    [0.055, 0.055) = 90 
    [0.055, 0.056) = 103 

  Percentiles, s/op:
      p(0.0000) =      0.050 s/op
     p(50.0000) =      0.054 s/op
     p(90.0000) =      0.055 s/op
     p(95.0000) =      0.055 s/op
     p(99.0000) =      0.055 s/op
     p(99.9000) =      0.055 s/op
     p(99.9900) =      0.055 s/op
     p(99.9990) =      0.055 s/op
     p(99.9999) =      0.055 s/op
    p(100.0000) =      0.055 s/op


# JMH version: 1.35
# VM version: JDK 15.0.2, Java HotSpot(TM) 64-Bit Server VM, 15.0.2+7-27
# VM invoker: /Library/Java/JavaVirtualMachines/jdk-15.0.2.jdk/Contents/Home/bin/java
# VM options: -Dfile.encoding=UTF-8 -XX:+ShowCodeDetailsInExceptionMessages
# Blackhole mode: full + dont-inline hint (auto-detected, use -Djmh.blackhole.autoDetect=false to disable)
# Warmup: 3 iterations, single-shot each
# Measurement: 4 iterations, single-shot each
# Timeout: 10 min per iteration
# Threads: 1 thread
# Benchmark mode: Single shot invocation time
# Benchmark: com.sample.app.BenchmarkingModes.measureSingleShotTime

# Run progress: 100.00% complete, ETA 00:00:00
# Fork: 1 of 1
# Warmup Iteration   1: 0.054 s/op
# Warmup Iteration   2: 0.050 s/op
# Warmup Iteration   3: 0.055 s/op
Iteration   1: 0.055 s/op
Iteration   2: 0.053 s/op
Iteration   3: 0.054 s/op
Iteration   4: 0.052 s/op


Result "com.sample.app.BenchmarkingModes.measureSingleShotTime":
  N = 4
  mean =      0.053 ±(99.9%) 0.008 s/op

  Histogram, s/op:
    [0.052, 0.052) = 1 
    [0.052, 0.053) = 0 
    [0.053, 0.053) = 0 
    [0.053, 0.053) = 0 
    [0.053, 0.053) = 1 
    [0.053, 0.054) = 0 
    [0.054, 0.054) = 1 
    [0.054, 0.054) = 0 
    [0.054, 0.054) = 0 
    [0.054, 0.055) = 0 
    [0.055, 0.055) = 0 
    [0.055, 0.055) = 0 
    [0.055, 0.055) = 1 
    [0.055, 0.056) = 0 
    [0.056, 0.056) = 0 

  Percentiles, s/op:
      p(0.0000) =      0.052 s/op
     p(50.0000) =      0.053 s/op
     p(90.0000) =      0.055 s/op
     p(95.0000) =      0.055 s/op
     p(99.0000) =      0.055 s/op
     p(99.9000) =      0.055 s/op
     p(99.9900) =      0.055 s/op
     p(99.9990) =      0.055 s/op
     p(99.9999) =      0.055 s/op
    p(100.0000) =      0.055 s/op


# Run complete. Total time: 00:03:31

REMEMBER: The numbers below are just data. To gain reusable insights, you need to follow up on
why the numbers are the way they are. Use profilers (see -prof, -lprof), design factorial
experiments, perform baseline and negative tests that provide experimental control, make sure
the benchmarking environment is safe on JVM/OS/HW level, ask for reviews from the domain experts.
Do not assume the numbers tell you what you want them to tell.

Benchmark                                                        Mode  Cnt   Score    Error  Units
BenchmarkingModes.measureThroughput                             thrpt    4  18.876 ±  0.433  ops/s
BenchmarkingModes.measureAverageTime                             avgt    4   0.053 ±  0.001   s/op
BenchmarkingModes.measureSampleTime                            sample  755   0.053 ±  0.001   s/op
BenchmarkingModes.measureSampleTime:measureSampleTime·p0.00    sample        0.050            s/op
BenchmarkingModes.measureSampleTime:measureSampleTime·p0.50    sample        0.054            s/op
BenchmarkingModes.measureSampleTime:measureSampleTime·p0.90    sample        0.055            s/op
BenchmarkingModes.measureSampleTime:measureSampleTime·p0.95    sample        0.055            s/op
BenchmarkingModes.measureSampleTime:measureSampleTime·p0.99    sample        0.055            s/op
BenchmarkingModes.measureSampleTime:measureSampleTime·p0.999   sample        0.055            s/op
BenchmarkingModes.measureSampleTime:measureSampleTime·p0.9999  sample        0.055            s/op
BenchmarkingModes.measureSampleTime:measureSampleTime·p1.00    sample        0.055            s/op
BenchmarkingModes.measureSingleShotTime                            ss    4   0.053 ±  0.008   s/op






 

 

Previous                                                 Next                                                 Home

JMH: Configure a Fork with OptionsBuilder

OptionsBuilder is used to configure a Fork.

 

Example

Options opt = new OptionsBuilder()
.include(OptionsBuilderDemo.class.getSimpleName())
.forks(1)
.measurementIterations(4)
.warmupIterations(3)
.resultFormat(ResultFormatType.JSON)
.build();

 

Above snippet notify JMH to run the bench mark with one fork, where there are

a.   3 warmup iterations,

b.   4 actual iterations

c.    Result format is of type json.

 

Find the below working application.

 


OptionsBuilderDemo.java

 

package com.sample.app;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.results.format.ResultFormatType;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

public class OptionsBuilderDemo {
	private static final String INPUT_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	private static SecureRandom SECURE_RANDOM = new SecureRandom();
	private static final int RAND_STR_LENGTH = 16;

	@Benchmark
	public String randString() throws InterruptedException {

		// Some intentional delay
		TimeUnit.MILLISECONDS.sleep(10);
		final StringBuilder sb = new StringBuilder(RAND_STR_LENGTH);

		for (int i = 0; i < RAND_STR_LENGTH; i++)
			sb.append(INPUT_CHARS.charAt(SECURE_RANDOM.nextInt(INPUT_CHARS.length())));

		return sb.toString();
	}

	public static void main(String[] args) throws RunnerException {
		Options opt = new OptionsBuilder()
				.include(OptionsBuilderDemo.class.getSimpleName())
				.forks(1)
				.measurementIterations(4)
				.warmupIterations(3)
				.resultFormat(ResultFormatType.JSON)
				.build();

		new Runner(opt).run();
	}

}

Output

# JMH version: 1.35
# VM version: JDK 15.0.2, Java HotSpot(TM) 64-Bit Server VM, 15.0.2+7-27
# VM invoker: /Library/Java/JavaVirtualMachines/jdk-15.0.2.jdk/Contents/Home/bin/java
# VM options: -Dfile.encoding=UTF-8 -XX:+ShowCodeDetailsInExceptionMessages
# Blackhole mode: full + dont-inline hint (auto-detected, use -Djmh.blackhole.autoDetect=false to disable)
# Warmup: 3 iterations, 10 s each
# Measurement: 4 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Throughput, ops/time
# Benchmark: com.sample.app.OptionsBuilderDemo.randString

# Run progress: 0.00% complete, ETA 00:01:10
# Fork: 1 of 1
# Warmup Iteration   1: 87.126 ops/s
# Warmup Iteration   2: 86.719 ops/s
# Warmup Iteration   3: 87.808 ops/s
Iteration   1: 87.395 ops/s
Iteration   2: 87.326 ops/s
Iteration   3: 86.841 ops/s
Iteration   4: 88.775 ops/s


Result "com.sample.app.OptionsBuilderDemo.randString":
  87.584 ±(99.9%) 5.373 ops/s [Average]
  (min, avg, max) = (86.841, 87.584, 88.775), stdev = 0.831
  CI (99.9%): [82.211, 92.957] (assumes normal distribution)


# Run complete. Total time: 00:01:15

REMEMBER: The numbers below are just data. To gain reusable insights, you need to follow up on
why the numbers are the way they are. Use profilers (see -prof, -lprof), design factorial
experiments, perform baseline and negative tests that provide experimental control, make sure
the benchmarking environment is safe on JVM/OS/HW level, ask for reviews from the domain experts.
Do not assume the numbers tell you what you want them to tell.

Benchmark                       Mode  Cnt   Score   Error  Units
OptionsBuilderDemo.randString  thrpt    4  87.584 ± 5.373  ops/s

Benchmark result is saved to jmh-result.json

 

From the output, you can confirm that the final result is saved to jmh-result.json file. Generated jms-result.json file is given below.

 

jmh-result.json

[
    {
        "jmhVersion" : "1.35",
        "benchmark" : "com.sample.app.OptionsBuilderDemo.randString",
        "mode" : "thrpt",
        "threads" : 1,
        "forks" : 1,
        "jvm" : "/Library/Java/JavaVirtualMachines/jdk-15.0.2.jdk/Contents/Home/bin/java",
        "jvmArgs" : [
            "-Dfile.encoding=UTF-8",
            "-XX:+ShowCodeDetailsInExceptionMessages"
        ],
        "jdkVersion" : "15.0.2",
        "vmName" : "Java HotSpot(TM) 64-Bit Server VM",
        "vmVersion" : "15.0.2+7-27",
        "warmupIterations" : 3,
        "warmupTime" : "10 s",
        "warmupBatchSize" : 1,
        "measurementIterations" : 4,
        "measurementTime" : "10 s",
        "measurementBatchSize" : 1,
        "primaryMetric" : {
            "score" : 87.58432197913439,
            "scoreError" : 5.373063970856802,
            "scoreConfidence" : [
                82.21125800827758,
                92.95738594999119
            ],
            "scorePercentiles" : {
                "0.0" : 86.84072256619667,
                "50.0" : 87.36057449834817,
                "90.0" : 88.77541635364449,
                "95.0" : 88.77541635364449,
                "99.0" : 88.77541635364449,
                "99.9" : 88.77541635364449,
                "99.99" : 88.77541635364449,
                "99.999" : 88.77541635364449,
                "99.9999" : 88.77541635364449,
                "100.0" : 88.77541635364449
            },
            "scoreUnit" : "ops/s",
            "rawData" : [
                [
                    87.39480245630831,
                    87.32634654038804,
                    86.84072256619667,
                    88.77541635364449
                ]
            ]
        },
        "secondaryMetrics" : {
        }
    }
]





 

 

Previous                                                 Next                                                 Home

Run benchmarks using JMH runner

 

Step 1: Create a benchmark.

@Benchmark
public String randString() throws InterruptedException {

	// Some intentional delay
	TimeUnit.MILLISECONDS.sleep(10);
	final StringBuilder sb = new StringBuilder(RAND_STR_LENGTH);

	for (int i = 0; i < RAND_STR_LENGTH; i++)
		sb.append(INPUT_CHARS.charAt(SECURE_RANDOM.nextInt(INPUT_CHARS.length())));

	return sb.toString();
}

 

Step 2: Define JMH Runner options.

Options opt = new OptionsBuilder()
.include(JMHRunnerDemo.class.getSimpleName())
.forks(1)
.measurementIterations(4)
.warmupIterations(3)
.build();

Step 3: Run the benchmark with Runner instance.

new Runner(opt).run();

Find the below working application.


 

JMHRunnerDemo.java

package com.sample.app;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

public class JMHRunnerDemo {
	private static final String INPUT_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	private static SecureRandom SECURE_RANDOM = new SecureRandom();
	private static final int RAND_STR_LENGTH = 16;

	@Benchmark
	public String randString() throws InterruptedException {

		// Some intentional delay
		TimeUnit.MILLISECONDS.sleep(10);
		final StringBuilder sb = new StringBuilder(RAND_STR_LENGTH);

		for (int i = 0; i < RAND_STR_LENGTH; i++)
			sb.append(INPUT_CHARS.charAt(SECURE_RANDOM.nextInt(INPUT_CHARS.length())));

		return sb.toString();
	}

	public static void main(String[] args) throws RunnerException {
		Options opt = new OptionsBuilder()
				.include(JMHRunnerDemo.class.getSimpleName())
				.forks(1)
				.measurementIterations(4)
				.warmupIterations(3)
				.build();

		new Runner(opt).run();
	}

}

Output

# JMH version: 1.35
# VM version: JDK 15.0.2, Java HotSpot(TM) 64-Bit Server VM, 15.0.2+7-27
# VM invoker: /Library/Java/JavaVirtualMachines/jdk-15.0.2.jdk/Contents/Home/bin/java
# VM options: -Dfile.encoding=UTF-8 -XX:+ShowCodeDetailsInExceptionMessages
# Blackhole mode: full + dont-inline hint (auto-detected, use -Djmh.blackhole.autoDetect=false to disable)
# Warmup: 3 iterations, 10 s each
# Measurement: 4 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Throughput, ops/time
# Benchmark: com.sample.app.JMHRunnerDemo.randString

# Run progress: 0.00% complete, ETA 00:01:10
# Fork: 1 of 1
# Warmup Iteration   1: 87.196 ops/s
# Warmup Iteration   2: 87.520 ops/s
# Warmup Iteration   3: 87.447 ops/s
Iteration   1: 86.724 ops/s
Iteration   2: 86.354 ops/s
Iteration   3: 86.534 ops/s
Iteration   4: 87.832 ops/s


Result "com.sample.app.JMHRunnerDemo.randString":
  86.861 ±(99.9%) 4.296 ops/s [Average]
  (min, avg, max) = (86.354, 86.861, 87.832), stdev = 0.665
  CI (99.9%): [82.566, 91.157] (assumes normal distribution)


# Run complete. Total time: 00:01:15

REMEMBER: The numbers below are just data. To gain reusable insights, you need to follow up on
why the numbers are the way they are. Use profilers (see -prof, -lprof), design factorial
experiments, perform baseline and negative tests that provide experimental control, make sure
the benchmarking environment is safe on JVM/OS/HW level, ask for reviews from the domain experts.
Do not assume the numbers tell you what you want them to tell.

Benchmark                  Mode  Cnt   Score   Error  Units
JMHRunnerDemo.randString  thrpt    4  86.861 ± 4.296  ops/s






 

 

 

Previous                                                 Next                                                 Home

Quick guide to JMH benchmarking

What is Microbenchmarking?

Microbenchmarking measures the performance of small piece of code.

 

For example, to measure the execution time of a method, we record the time when the method is about to start the actual execution (ex: say it is time1) and we record the time (say it is time2) when the method finish execution.

long time1 = System.currentTimeMillis();
	......
	......
	......
long time2 = System.currentTimeMillis();

 

(time2-time1) return the total execution time of a method. Result may not be accurate for one iteration, to get the better accurate result, we need to run the test several times, ignore the warmup time,  get the throughput, average execution time etc.,


Apart from this, you definitely expect following features from a benchmarking.

a.   We may need to store the benchmarking statistics to external destination like a file,

b.   we may want to publish these statistics in json or csv format etc.,

c.    Want to get the benchmarking results in different time units like nanoseconds, milliseconds, seconds etc.,

d.   Run the benchmarking with different parameters

e.   We may want to maintain the state across given trail of execution.

f.     We may want to ignore warmup executions from statistics calculation etc.,

 

 

What if I say, there is a tool JMH, that has all these features. Cool isn’t it…..

 

Let’s write a simple hello world application and try to understand JMH basics.


 

Step 1: Create a benchmark using @Benchmark annotation.

@Benchmark
@BenchmarkMode(Mode.AverageTime)
public String randString() throws InterruptedException {
	// Some intentional delay
	TimeUnit.MILLISECONDS.sleep(10);
	final StringBuilder sb = new StringBuilder(RAND_STR_LENGTH);

	for (int i = 0; i < RAND_STR_LENGTH; i++)
		sb.append(INPUT_CHARS.charAt(SECURE_RANDOM.nextInt(INPUT_CHARS.length())));

	return sb.toString();
}

Step 2: Start the benchmarking process by calling org.openjdk.jmh.Main.main method.

 

public static void main(String[] args) throws IOException {
    org.openjdk.jmh.Main.main(args);
}

Find the below working application.

 

HelloWorld.java

package com.sample.app;

import java.io.IOException;
import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;

public class HelloWorld {

	private static final String INPUT_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	private static SecureRandom SECURE_RANDOM = new SecureRandom();
	private static final int RAND_STR_LENGTH = 16;

	@Benchmark
	@BenchmarkMode(Mode.AverageTime)
	public String randString() throws InterruptedException {
		// Some intentional delay
		TimeUnit.MILLISECONDS.sleep(10);
		final StringBuilder sb = new StringBuilder(RAND_STR_LENGTH);

		for (int i = 0; i < RAND_STR_LENGTH; i++)
			sb.append(INPUT_CHARS.charAt(SECURE_RANDOM.nextInt(INPUT_CHARS.length())));

		return sb.toString();
	}

	public static void main(String[] args) throws IOException {
		org.openjdk.jmh.Main.main(args);
	}

}

Output

# JMH version: 1.35
# VM version: JDK 15.0.2, Java HotSpot(TM) 64-Bit Server VM, 15.0.2+7-27
# VM invoker: /Library/Java/JavaVirtualMachines/jdk-15.0.2.jdk/Contents/Home/bin/java
# VM options: -Dfile.encoding=UTF-8 -XX:+ShowCodeDetailsInExceptionMessages
# Blackhole mode: full + dont-inline hint (auto-detected, use -Djmh.blackhole.autoDetect=false to disable)
# Warmup: 5 iterations, 10 s each
# Measurement: 5 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: com.sample.app.HelloWorld.randString

# Run progress: 0.00% complete, ETA 00:08:20
# Fork: 1 of 5
# Warmup Iteration   1: 0.011 s/op
# Warmup Iteration   2: 0.011 s/op
# Warmup Iteration   3: 0.011 s/op
# Warmup Iteration   4: 0.011 s/op
# Warmup Iteration   5: 0.011 s/op
Iteration   1: 0.011 s/op
Iteration   2: 0.011 s/op
Iteration   3: 0.011 s/op
Iteration   4: 0.011 s/op
Iteration   5: 0.011 s/op

# Run progress: 20.00% complete, ETA 00:07:01
# Fork: 2 of 5
# Warmup Iteration   1: 0.011 s/op
# Warmup Iteration   2: 0.011 s/op
# Warmup Iteration   3: 0.011 s/op
# Warmup Iteration   4: 0.011 s/op
# Warmup Iteration   5: 0.011 s/op
Iteration   1: 0.011 s/op
Iteration   2: 0.011 s/op
Iteration   3: 0.011 s/op
Iteration   4: 0.011 s/op
Iteration   5: 0.011 s/op

# Run progress: 40.00% complete, ETA 00:05:16
# Fork: 3 of 5
# Warmup Iteration   1: 0.011 s/op
# Warmup Iteration   2: 0.011 s/op
# Warmup Iteration   3: 0.011 s/op
# Warmup Iteration   4: 0.011 s/op
# Warmup Iteration   5: 0.011 s/op
Iteration   1: 0.011 s/op
Iteration   2: 0.011 s/op
Iteration   3: 0.011 s/op
Iteration   4: 0.011 s/op
Iteration   5: 0.011 s/op

# Run progress: 60.00% complete, ETA 00:03:30
# Fork: 4 of 5
# Warmup Iteration   1: 0.011 s/op
# Warmup Iteration   2: 0.011 s/op
# Warmup Iteration   3: 0.011 s/op
# Warmup Iteration   4: 0.011 s/op
# Warmup Iteration   5: 0.011 s/op
Iteration   1: 0.011 s/op
Iteration   2: 0.011 s/op
Iteration   3: 0.011 s/op
Iteration   4: 0.011 s/op
Iteration   5: 0.011 s/op

# Run progress: 80.00% complete, ETA 00:01:45
# Fork: 5 of 5
# Warmup Iteration   1: 0.011 s/op
# Warmup Iteration   2: 0.011 s/op
# Warmup Iteration   3: 0.011 s/op
# Warmup Iteration   4: 0.011 s/op
# Warmup Iteration   5: 0.011 s/op
Iteration   1: 0.011 s/op
Iteration   2: 0.011 s/op
Iteration   3: 0.011 s/op
Iteration   4: 0.011 s/op
Iteration   5: 0.011 s/op


Result "com.sample.app.HelloWorld.randString":
  0.011 ±(99.9%) 0.001 s/op [Average]
  (min, avg, max) = (0.011, 0.011, 0.011), stdev = 0.001
  CI (99.9%): [0.011, 0.011] (assumes normal distribution)


# Run complete. Total time: 00:08:47

REMEMBER: The numbers below are just data. To gain reusable insights, you need to follow up on
why the numbers are the way they are. Use profilers (see -prof, -lprof), design factorial
experiments, perform baseline and negative tests that provide experimental control, make sure
the benchmarking environment is safe on JVM/OS/HW level, ask for reviews from the domain experts.
Do not assume the numbers tell you what you want them to tell.

Benchmark              Mode  Cnt  Score    Error  Units
HelloWorld.randString  avgt   25  0.011 ±  0.001   s/op

In the above output, you can see that it took 8 minutes to calculate the average execution time of randString method. It did five forks with 5 warmup iterations and 5 actual iterations. From those results, it's concluding an output by taking the average of all execution. So the result is almost accurate here.

 

Now let’s understand the JMH concepts in depth.

 

Fork

Fork represent a trail, where each trail has m warmup iterations and n actual iterations. In the above example, JMH perform 5 trails. You can customize the number of forks using either @Fork annotation or with OptionBuilder.


@Benchmark
@Fork(2)
@BenchmarkMode(Mode.AverageTime)
public String randString() throws InterruptedException {
	......
	......
}

Above snippet configure 2 trails to benchmark the method randString().

 

Warmup

The warmup iterations are used to ensure your application reaches a steady state before recording sample values. You can configure the number of warmup iterations for each fork using @Warmup annotation. 

@Benchmark
@Fork(value = 2)
@Warmup(iterations = 2)
@BenchmarkMode(Mode.AverageTime)
public String randString() throws InterruptedException {
	..........
	..........
}

Console output for above configuration.

# Benchmark: com.sample.app.HelloWorld.randString

# Run progress: 0.00% complete, ETA 00:02:20
# Fork: 1 of 2
# Warmup Iteration   1: 0.011 s/op
# Warmup Iteration   2: 0.011 s/op
Iteration   1: 0.012 s/op
Iteration   2: 0.011 s/op
Iteration   3: 0.011 s/op
Iteration   4: 0.011 s/op
Iteration   5: 0.011 s/op

# Run progress: 50.00% complete, ETA 00:01:10
# Fork: 2 of 2
# Warmup Iteration   1: 0.011 s/op
# Warmup Iteration   2: 0.011 s/op
Iteration   1: 0.011 s/op
Iteration   2: 0.011 s/op
Iteration   3: 0.011 s/op
Iteration   4: 0.011 s/op
Iteration   5: 0.011 s/op

Actual iterations

Actual iterations to calculate the benchmark are set with the help of @Measurement annotation.

@Benchmark
@Fork(value = 2)
@Warmup(iterations = 2)
@Measurement(iterations = 8)
@BenchmarkMode(Mode.AverageTime)
public String randString() throws InterruptedException {
	......
	......
}

Above snippet sets number of warmup iterations to 2, and number of actual iterations to 8 for each fork.

 

Console output for above configuration.

# Benchmark: com.sample.app.HelloWorld.randString

# Run progress: 0.00% complete, ETA 00:03:20
# Fork: 1 of 2
# Warmup Iteration   1: 0.011 s/op
# Warmup Iteration   2: 0.011 s/op
Iteration   1: 0.011 s/op
Iteration   2: 0.011 s/op
Iteration   3: 0.011 s/op
Iteration   4: 0.011 s/op
Iteration   5: 0.011 s/op
Iteration   6: 0.011 s/op
Iteration   7: 0.012 s/op
Iteration   8: 0.011 s/op

# Run progress: 50.00% complete, ETA 00:01:40
# Fork: 2 of 2
# Warmup Iteration   1: 0.011 s/op
# Warmup Iteration   2: 0.011 s/op
Iteration   1: 0.011 s/op
Iteration   2: 0.011 s/op
Iteration   3: 0.011 s/op
Iteration   4: 0.011 s/op
Iteration   5: 0.011 s/op
Iteration   6: 0.011 s/op
Iteration   7: 0.011 s/op
Iteration   8: 0.011 s/op

Note that, JMH forks the JVM multiple times during benchmarking in order to discard any profiles built up by the just-in-time (JIT) profiling performed by the JVM during execution.

 

 

Previous                                                 Next                                                 Home