DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Building AI Applications With Java and Gradle
  • How To Add Three Photo Filters to Your Applications in Java
  • How To Convert HTML to PNG in Java
  • Deploying a Kotlin App to Heroku

Trending

  • Using Java Stream Gatherers To Improve Stateful Operations
  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD
  • Agile’s Quarter-Century Crisis
  • Traditional Testing and RAGAS: A Hybrid Strategy for Evaluating AI Chatbots
  1. DZone
  2. Coding
  3. Java
  4. Use JMH for Your Java Applications With Gradle

Use JMH for Your Java Applications With Gradle

If you want to benchmark your code, the Java Microbenchmark Harness is the tool of choice. See an example here using the refill-rate-limiter project.

By 
Emmanouil Gkatziouras user avatar
Emmanouil Gkatziouras
DZone Core CORE ·
Nov. 03, 22 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
9.1K Views

Join the DZone community and get the full member experience.

Join For Free

If you want to benchmark your code, the Java Microbenchmark Harness is the tool of choice.Java logo
In our example, we will use the refill-rate-limiter project. 

Since refill-rate-limiter uses Gradle, we will use the following plugin for Gradle:

Java
 
plugins {
...
  id "me.champeau.gradle.jmh" version "0.5.3"
...
}


We will place the benchmark in the jmh/java/io/github/resilience4j/ratelimiter folder.

Our benchmark should look like this:

Java
 
package io.github.resilience4j.ratelimiter;
 
import io.github.resilience4j.ratelimiter.internal.RefillRateLimiter;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.profile.GCProfiler;
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;
 
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
 
@State(Scope.Benchmark)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@BenchmarkMode(Mode.All)
public class RateLimiterBenchmark {
 
    private static final int FORK_COUNT = 2;
    private static final int WARMUP_COUNT = 10;
    private static final int ITERATION_COUNT = 10;
    private static final int THREAD_COUNT = 2;
 
    private RefillRateLimiter refillRateLimiter;
 
    private Supplier<String> refillGuardedSupplier;
 
    public static void main(String[] args) throws RunnerException {
        Options options = new OptionsBuilder()
                .addProfiler(GCProfiler.class)
                .build();
        new Runner(options).run();
    }
 
    @Setup
    public void setUp() {
 
        RefillRateLimiterConfig refillRateLimiterConfig = RefillRateLimiterConfig.custom()
                                                                                 .limitForPeriod(1)
                                                                                 .limitRefreshPeriod(Duration.ofNanos(1))
                                                                                 .timeoutDuration(Duration.ofSeconds(5))
                                                                                 .build();
 
        refillRateLimiter = new RefillRateLimiter("refillBased", refillRateLimiterConfig);
 
        Supplier<String> stringSupplier = () -> {
            Blackhole.consumeCPU(1);
            return "Hello Benchmark";
        };
 
        refillGuardedSupplier = RateLimiter.decorateSupplier(refillRateLimiter, stringSupplier);
    }
 
    @Benchmark
    @Threads(value = THREAD_COUNT)
    @Warmup(iterations = WARMUP_COUNT)
    @Fork(value = FORK_COUNT)
    @Measurement(iterations = ITERATION_COUNT)
    public String refillPermission() {
        return refillGuardedSupplier.get();
    }
 
}


Let’s now check the elements one by one.

By using benchmark scope, all of the threads used on the benchmark scope will share the same object. We do so because we want to test how refill-rate-limiter performs in a multithreaded scenario.

Java
 
@State(Scope.Benchmark)


We would like our results to be reported in microseconds, therefore we shall use the OutputTimeUnit.

Java
 
@OutputTimeUnit(TimeUnit.MICROSECONDS)


On JMH, we have various benchmark modes depending on what we want to measure.

  • Throughput is when we want to measure the number of operations per unit of time.
  • AverageTime is when we want to measure the average time per operation.
  • SampleTime is when we want to sample the time for each operation including min, max time, and more than just the average.
  • SingleShotTime is when we want to measure the time for a single operation. This can help when we want to identify how the operation will do on a cold start.

We also have the option to measure all of the above.

Java
 
@BenchmarkMode(Mode.All)


Those options configured on the class level will apply to the benchmark methods we will add.

Let’s also examine how the benchmark will run. We will specify the number of threads by using the @Threads annotation.

Java
 
@Threads(value = THREAD_COUNT)


Also, we want to warm up before we run the actual benchmarks. This way our code will be initialized, online optimizations will take place, and our runtime will adapt to the conditions before we run the benchmarks.

Java
 
@Warmup(iterations = WARMUP_COUNT)


Using @Fork we will instruct how many times the benchmark will run.

Java
 
@Fork(value = FORK_COUNT)


Then we need to specify the number of iterations we want to measure:

Java
 
@Measurement(iterations = ITERATION_COUNT)


We can start our test by just using:

Java
 
gradle jmh


The results will be saved in a file.

Java
 
...
2022-10-28T09:08:44.522+0100 [QUIET] [system.out] Benchmark result is saved to /path/refill-rate-limiter/build/reports/jmh/results.txt
..


Let’s examine the results.

Shell
 
Benchmark                                                         Mode       Cnt      Score   Error   Units
RateLimiterBenchmark.refillPermission                            thrpt        20     13.594 ± 0.217  ops/us
RateLimiterBenchmark.refillPermission                             avgt        20      0.147 ± 0.002   us/op
RateLimiterBenchmark.refillPermission                           sample  10754462      0.711 ± 0.025   us/op
RateLimiterBenchmark.refillPermission:refillPermission·p0.00    sample                  ≈ 0           us/op
RateLimiterBenchmark.refillPermission:refillPermission·p0.50    sample                0.084           us/op
RateLimiterBenchmark.refillPermission:refillPermission·p0.90    sample                0.125           us/op
RateLimiterBenchmark.refillPermission:refillPermission·p0.95    sample                0.125           us/op
RateLimiterBenchmark.refillPermission:refillPermission·p0.99    sample                0.209           us/op
RateLimiterBenchmark.refillPermission:refillPermission·p0.999   sample              139.008           us/op
RateLimiterBenchmark.refillPermission:refillPermission·p0.9999  sample              935.936           us/op
RateLimiterBenchmark.refillPermission:refillPermission·p1.00    sample            20709.376           us/op
RateLimiterBenchmark.refillPermission    


As we can see, we have the modes listed.

Countis the number of iterations. Apart from throughput where we measure the operations by time, the rest is the time per operation. Throughput, Average, and Single shot are straightforward. Sample lists the percentiles. Error is the margin of error.

That’s it! Happy benchmarking!

Gradle Java (programming language)

Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Building AI Applications With Java and Gradle
  • How To Add Three Photo Filters to Your Applications in Java
  • How To Convert HTML to PNG in Java
  • Deploying a Kotlin App to Heroku

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!