Advertisement
GreyCat

Untitled

Aug 25th, 2011
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.86 KB | None | 0 0
  1. import java.util.Random;
  2.  
  3. public class TestLoops {
  4.     public static final int VECTOR_SIZE = 10000;
  5.     public static final int TRIES = 10;
  6.     public static final int N = 10000000;
  7.  
  8.     static int forwardLoop(int v[]) {
  9.         int s = 0;
  10.         for (int i = 0; i < v.length; i++)
  11.             s += v[i];
  12.         return s;
  13.     }
  14.  
  15.     static int revLoop(int v[]) {
  16.         int s = 0;
  17.         for (int i = v.length - 1; i >= 0; i--)
  18.             s += v[i];
  19.         return s;
  20.     }
  21.  
  22.     static int revLoop2(int v[]) {
  23.         int s = 0;
  24.         for (int i = v.length; --i >= 0; )
  25.             s += v[i];
  26.         return s;
  27.     }
  28.  
  29.     public static void main(String[] args) {
  30.         long t1, t2;
  31.         Random r = new Random(42);
  32.         int[] v = new int[VECTOR_SIZE];
  33.         for (int i = 0; i < v.length; i++)
  34.             v[i] = r.nextInt(1000);
  35.  
  36.         int goodSum = forwardLoop(v);
  37.  
  38.         for (int test = 0; test < TRIES; test++) {
  39.             t1 = System.currentTimeMillis();
  40.             for (int j = 0; j < N; j++) {
  41.                 if (forwardLoop(v) != goodSum)
  42.                     throw new RuntimeException();
  43.             }
  44.             t2 = System.currentTimeMillis();
  45.             System.out.println("d1 = " + (t2 - t1));
  46.  
  47.             t1 = System.currentTimeMillis();
  48.             for (int j = 0; j < N; j++) {
  49.                 if (revLoop(v) != goodSum)
  50.                     throw new RuntimeException();
  51.             }
  52.             t2 = System.currentTimeMillis();
  53.             System.out.println("d2 = " + (t2 - t1));
  54.  
  55.             t1 = System.currentTimeMillis();
  56.             for (int j = 0; j < N; j++) {
  57.                 if (revLoop2(v) != goodSum)
  58.                     throw new RuntimeException();
  59.             }
  60.             t2 = System.currentTimeMillis();
  61.             System.out.println("d3 = " + (t2 - t1));
  62.         }
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement