Created
March 31, 2016 08:37
-
-
Save KeenS/88bb5a77fb65ac64620577374ac6d22d to your computer and use it in GitHub Desktop.
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
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); | |
} | |
} | |
} |
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
$ 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