Last active
November 29, 2024 08:53
-
-
Save Genzer/9cdd0768e45b371a9813c9ac71960107 to your computer and use it in GitHub Desktop.
Microbenchmarking using JBang and JMH
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//DEPS org.openjdk.jmh:jmh-generator-annprocess:1.36 | |
// --javaagent=ap-loader@maxandersen=start,event=cpu,file=profile.html | |
package com.grokhard.benchmarking; | |
import org.openjdk.jmh.*; | |
import org.openjdk.jmh.annotations.*; | |
import org.openjdk.jmh.infra.Blackhole; | |
import java.util.stream.*; | |
import java.util.*; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* This is just an example of using Java Microbenchmark Harness (JHM) used in conjunction with JBang | |
* to demonstrate how simple it is to do that without heavy tool like Maven or Gradle. | |
* | |
* RUN: | |
* jbang Loops.java | |
* | |
* This chooses a scenario: sum 10,000 numbers from a list. There are 4 bechmarks of how to use the loops. | |
* | |
* The use of Blackhole is important to avoid Dead Code Elimination of Java Compiler. | |
*/ | |
@State(Scope.Benchmark) | |
@OutputTimeUnit(TimeUnit.NANOSECONDS) | |
public class Loops { | |
public static void main(String[] args) throws java.io.IOException { | |
org.openjdk.jmh.Main.main(args); | |
} | |
private List<Integer> numbers; | |
@Setup(Level.Iteration) | |
public void setup() { | |
numbers = IntStream.range(0, 10_000).boxed().toList(); | |
} | |
@Fork(value = 1) | |
@Warmup(iterations = 5) | |
@Benchmark | |
@BenchmarkMode(Mode.AverageTime) | |
public void sumUsingForEnhanceLoop(Blackhole bh) { | |
int sum = 0; | |
for (Integer number : numbers) { | |
sum += number; | |
} | |
bh.consume(sum); | |
} | |
@Fork(value = 1) | |
@Warmup(iterations = 5) | |
@Benchmark | |
@BenchmarkMode(Mode.AverageTime) | |
public void sumUsingForLoopWithMethodCall(Blackhole bh) { | |
int sum = 0; | |
for (int i = 0; i < numbers.size(); i++) { | |
sum += numbers.get(i); | |
} | |
bh.consume(sum); | |
} | |
@Fork(value = 1) | |
@Warmup(iterations = 5) | |
@Benchmark | |
@BenchmarkMode(Mode.AverageTime) | |
public void sumUsingForLoopWithSizeGotOutOfLoop(Blackhole bh) { | |
int sum = 0; | |
int size = numbers.size(); | |
for (int i = 0; i < size; i++) { | |
sum += numbers.get(i); | |
} | |
bh.consume(sum); | |
} | |
@Fork(value = 1) | |
@Warmup(iterations = 5) | |
@Benchmark | |
@BenchmarkMode(Mode.AverageTime) | |
public void sumUsingReverseForLoopWithSizeGotOutOfLoop(Blackhole bh) { | |
int sum = 0; | |
int size = numbers.size(); | |
for (int i = size - 1; i >= 0; i--) { | |
sum += numbers.get(i); | |
} | |
bh.consume(sum); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment