Skip to content

Instantly share code, notes, and snippets.

@KeenS
Created March 31, 2016 08:37
Show Gist options
  • Save KeenS/88bb5a77fb65ac64620577374ac6d22d to your computer and use it in GitHub Desktop.
Save KeenS/88bb5a77fb65ac64620577374ac6d22d to your computer and use it in GitHub Desktop.
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.time.ZoneId;
import java.time.Instant;
public abstract class Benchmark {
final String name;
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").
withZone(ZoneId.of("Asia/Tokyo"));
public Benchmark(String name) {
this.name = name;
}
abstract long run(int iterations) throws Throwable;
private BigDecimal time() {
try {
int nextI = 1;
int i;
long duration;
do {
i = nextI;
long start = System.nanoTime();
run(i);
duration = System.nanoTime() - start;
nextI = (i << 1) | 1;
} while (duration < 100000000 && nextI > 0);
return new BigDecimal((duration) * 1000 / i).movePointLeft(3);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
@Override
public String toString() {
return name + "\t" + time() + " ns";
}
public static void main(String[] args) throws Exception {
Benchmark[] benchmarks = {
new Benchmark("try") {
@Override long run(int iterations) throws Throwable {
long x = 0;
for (int i = 0; i < iterations; i++) {
try {
x += Instant.from(format.parse("2015-12-30 17:57:03")).toEpochMilli();
} catch (Exception e) {
e.printStackTrace();
}
}
return x;
}
}, new Benchmark("no try") {
@Override long run(int iterations) throws Throwable {
long x = 0;
for (int i = 0; i < iterations; i++) {
x += Instant.from(format.parse("2015-12-30 17:57:03")).toEpochMilli();
}
return x;
}
}
};
for (Benchmark bm : benchmarks) {
System.out.println(bm);
}
}
}
$ javac Benchmark.java
$ java Benchmark
try 4305.802 ns
no try 874.378 ns
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment