Skip to content

Instantly share code, notes, and snippets.

@YuriDenison
Created October 23, 2016 15:37
Show Gist options
  • Save YuriDenison/bca68914e69887cb8874ae51f18168b0 to your computer and use it in GitHub Desktop.
Save YuriDenison/bca68914e69887cb8874ae51f18168b0 to your computer and use it in GitHub Desktop.
Loop JMH Test
package com.denison;
import org.openjdk.jmh.annotations.*;
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.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author Yuri Denison
* @since 23.10.2016
*/
@State(Scope.Benchmark)
@Warmup(iterations = 5, timeUnit = TimeUnit.NANOSECONDS)
@Measurement(iterations = 10, timeUnit = TimeUnit.NANOSECONDS)
@Fork(value = 1)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class LoopTest {
private static final int RUNS = 1000;
private static final int SIZE = 1_000_000_0;
private static final List<Integer> VALUES = new ArrayList<>(SIZE);
static {
Collections.fill(VALUES, 1);
}
@Benchmark
@OperationsPerInvocation(RUNS)
public long traditionalLoop() {
long sum = 0;
for (int i = 0; i < VALUES.size(); i++) {
sum += VALUES.get(i);
}
return sum;
}
@Benchmark
@OperationsPerInvocation(RUNS)
public long traditionalLoopOptimized() {
long sum = 0;
int size = VALUES.size();
for (int i = 0; i < size; i++) {
sum += VALUES.get(i);
}
return sum;
}
@Benchmark
@OperationsPerInvocation(RUNS)
public long foreachLoop() {
long sum = 0;
for (int value : VALUES) {
sum += value;
}
return sum;
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(".*" + LoopTest.class.getSimpleName() + ".*")
.build();
new Runner(opt).run();
}
}
# JMH 1.15 (released 23 days ago)
# VM version: JDK 1.8.0_102, VM 25.102-b14
# VM invoker: /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/bin/java
# VM options: -Didea.launcher.port=7537 -Didea.launcher.bin.path=/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8
# Warmup: 5 iterations, 1 s each
# Measurement: 10 iterations, 1 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Throughput, ops/time
Benchmark Mode Cnt Score Error Units
LoopTest.foreachLoop thrpt 10 280.758 ± 11.071 ops/ns
LoopTest.traditionalLoop thrpt 10 320.631 ± 14.032 ops/ns
LoopTest.traditionalLoopOptimized thrpt 10 311.157 ± 15.439 ops/ns
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment