Skip to content

Instantly share code, notes, and snippets.

@amir343
Last active May 6, 2016 18:14
Show Gist options
  • Save amir343/9018106 to your computer and use it in GitHub Desktop.
Save amir343/9018106 to your computer and use it in GitHub Desktop.
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.List;
import java.util.Random;
import java.util.stream.IntStream;
/**
* Using JDK 8 build b129
*/
@State(Scope.Thread)
public class Benchmark {
List<Person> persons = new ArrayList<>();
@Setup
public void init() {
Random random = new Random();
IntStream.range(0, 10000).forEach( a -> {
persons.add(new Person(random.nextInt(100)));
});
}
@GenerateMicroBenchmark
public void non_functional() {
long sum = 0;
for (Person person : persons) {
sum += person.age;
}
}
@GenerateMicroBenchmark
public void functional() {
persons.stream().map( p -> p.age ).reduce( (a, b) -> a + b ).get();
}
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(".*" + Benchmark.class.getSimpleName() + ".*")
.shouldDoGC(true)
.shouldFailOnError(true)
.mode(Mode.All)
.warmupIterations(1)
.measurementIterations(10)
.forks(1)
.build();
new Runner(options).run();
}
/**
*
*/
static class Person {
Person(int age) {
this.age = age;
}
int age;
}
}
Machine: OSx 10.9.1 (3 GHz Intel Core i7, L2 Cache 256 KB, L3 Cache 4 MB)
JMH version 0.2.1
Benchmark Mode Samples Mean Mean error Units
s.Benchmark.functional thrpt 10 9.561 0.184 ops/ms
s.Benchmark.non_functional thrpt 10 123.471 3.601 ops/ms
s.Benchmark.functional avgt 10 0.122 0.001 ms/op
s.Benchmark.non_functional avgt 10 0.008 0.000 ms/op
s.Benchmark.functional sample 94905 0.105 0.000 ms/op
s.Benchmark.non_functional sample 1202292 0.008 0.000 ms/op
s.Benchmark.functional ss 10 0.499 0.250 ms
s.Benchmark.non_functional ss 10 0.678 0.475 ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment