Advertisement
Guest User

int vs long vs short benchmark

a guest
Aug 28th, 2014
353
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.82 KB | None | 0 0
  1. package benchmark;
  2.  
  3. public class Bench {
  4.     private static final int ITERATIONS = 1000000000;
  5.  
  6.     public static void main(String[] args) {
  7.         benchmarkInt();
  8.         benchmarkLong();
  9.         benchmarkShort();
  10.     }
  11.  
  12.     private static void benchmarkInt() {
  13.         // Create two variables that both equal 1, but that the compiler won't
  14.         // optimize away inside the loop.
  15.         final int a = (int)Math.ceil(Math.random());
  16.         final int b = (int)Math.ceil(Math.random());
  17.         // Do the benchmark three times, allowing the user to see the variation.
  18.         for (int test = 0; test < 3; test++) {
  19.             int t = 0;
  20.             long start = System.nanoTime();
  21.             for (int i = 0; i < ITERATIONS; i++) {
  22.                 t += a;
  23.                 t -= b;
  24.             }
  25.             long duration = System.nanoTime() - start;
  26.             // Print benchmark result. First result should probably be ignored,
  27.             // it's the warmup phase.
  28.             System.out.println("int: " + duration / 1000000 + " ms. Calculation result: " + t);
  29.         }
  30.     }
  31.  
  32.     private static void benchmarkLong() {
  33.         final long a = (long)Math.ceil(Math.random());
  34.         final long b = (long)Math.ceil(Math.random());
  35.         for (int test = 0; test < 3; test++) {
  36.             long t = 0;
  37.             long start = System.nanoTime();
  38.             for (int i = 0; i < ITERATIONS; i++) {
  39.                 t += a;
  40.                 t -= b;
  41.             }
  42.             long duration = System.nanoTime() - start;
  43.             System.out.println("long: " + duration / 1000000 + " ms. Calculation result: " + t);
  44.         }
  45.     }
  46.  
  47.     private static void benchmarkShort() {
  48.         final short a = (short)Math.ceil(Math.random());
  49.         final short b = (short)Math.ceil(Math.random());
  50.         for (int test = 0; test < 3; test++) {
  51.             short t = 0;
  52.             long start = System.nanoTime();
  53.             for (int i = 0; i < ITERATIONS; i++) {
  54.                 t += a;
  55.                 t -= b;
  56.             }
  57.             long duration = System.nanoTime() - start;
  58.             System.out.println("short: " + duration / 1000000 + " ms. Calculation result: " + t);
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement