Skip to content

Instantly share code, notes, and snippets.

@iaveryanov
Created June 16, 2014 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iaveryanov/bff6e6c18f41168e1bc3 to your computer and use it in GitHub Desktop.
Save iaveryanov/bff6e6c18f41168e1bc3 to your computer and use it in GitHub Desktop.
package ru.int_overflow;
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.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class IntOverflowPuzzleJmh {
@GenerateMicroBenchmark
public int count_int_to_max() {
int counter = 0;
int max = Integer.MAX_VALUE;
while (counter != max) {
++counter;
}
return counter;
}
@GenerateMicroBenchmark
public int count_int_overflow() {
int counter = 0;
int max = Integer.MAX_VALUE + 1; // <- It is overflow! to Integer.MIN_VALUE!
while (counter != max) {
++counter;
}
return counter;
}
@GenerateMicroBenchmark
public long count_long() {
long counter = 0;
int max = Integer.MAX_VALUE;
while (counter != max) {
++counter;
}
return counter;
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(".*" + IntOverflowPuzzleJmh.class.getSimpleName() + ".*")
// .verbosity(VerboseMode.SILENT)
.warmupIterations(3)
.measurementIterations(5)
.threads(1)
.forks(1)
.build();
new Runner(opt).run();
}
}
@LexaChebara
Copy link

Intel Core i7, Ubuntu 12.0 LTS, Java 7

Benchmark Mode Samples Score Score error Units
o.s.MyBenchmark.count_int_overflow avgt 200 817931688.065 7959319.632 ns/op
o.s.MyBenchmark.count_int_to_max avgt 200 0.588 0.007 ns/op
o.s.MyBenchmark.count_long avgt 200 640244617.558 25173704.966 ns/op

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment