Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package benchmark;
- public class Bench {
- private static final int ITERATIONS = 1000000000;
- public static void main(String[] args) {
- benchmarkInt();
- benchmarkLong();
- benchmarkShort();
- }
- private static void benchmarkInt() {
- // Create two variables that both equal 1, but that the compiler won't
- // optimize away inside the loop.
- final int a = (int)Math.ceil(Math.random());
- final int b = (int)Math.ceil(Math.random());
- // Do the benchmark three times, allowing the user to see the variation.
- for (int test = 0; test < 3; test++) {
- int t = 0;
- long start = System.nanoTime();
- for (int i = 0; i < ITERATIONS; i++) {
- t += a;
- t -= b;
- }
- long duration = System.nanoTime() - start;
- // Print benchmark result. First result should probably be ignored,
- // it's the warmup phase.
- System.out.println("int: " + duration / 1000000 + " ms. Calculation result: " + t);
- }
- }
- private static void benchmarkLong() {
- final long a = (long)Math.ceil(Math.random());
- final long b = (long)Math.ceil(Math.random());
- for (int test = 0; test < 3; test++) {
- long t = 0;
- long start = System.nanoTime();
- for (int i = 0; i < ITERATIONS; i++) {
- t += a;
- t -= b;
- }
- long duration = System.nanoTime() - start;
- System.out.println("long: " + duration / 1000000 + " ms. Calculation result: " + t);
- }
- }
- private static void benchmarkShort() {
- final short a = (short)Math.ceil(Math.random());
- final short b = (short)Math.ceil(Math.random());
- for (int test = 0; test < 3; test++) {
- short t = 0;
- long start = System.nanoTime();
- for (int i = 0; i < ITERATIONS; i++) {
- t += a;
- t -= b;
- }
- long duration = System.nanoTime() - start;
- System.out.println("short: " + duration / 1000000 + " ms. Calculation result: " + t);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement