Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- public class TestLoops {
- public static final int VECTOR_SIZE = 10000;
- public static final int TRIES = 10;
- public static final int N = 10000000;
- static int forwardLoop(int v[]) {
- int s = 0;
- for (int i = 0; i < v.length; i++)
- s += v[i];
- return s;
- }
- static int revLoop(int v[]) {
- int s = 0;
- for (int i = v.length - 1; i >= 0; i--)
- s += v[i];
- return s;
- }
- static int revLoop2(int v[]) {
- int s = 0;
- for (int i = v.length; --i >= 0; )
- s += v[i];
- return s;
- }
- public static void main(String[] args) {
- long t1, t2;
- Random r = new Random(42);
- int[] v = new int[VECTOR_SIZE];
- for (int i = 0; i < v.length; i++)
- v[i] = r.nextInt(1000);
- int goodSum = forwardLoop(v);
- for (int test = 0; test < TRIES; test++) {
- t1 = System.currentTimeMillis();
- for (int j = 0; j < N; j++) {
- if (forwardLoop(v) != goodSum)
- throw new RuntimeException();
- }
- t2 = System.currentTimeMillis();
- System.out.println("d1 = " + (t2 - t1));
- t1 = System.currentTimeMillis();
- for (int j = 0; j < N; j++) {
- if (revLoop(v) != goodSum)
- throw new RuntimeException();
- }
- t2 = System.currentTimeMillis();
- System.out.println("d2 = " + (t2 - t1));
- t1 = System.currentTimeMillis();
- for (int j = 0; j < N; j++) {
- if (revLoop2(v) != goodSum)
- throw new RuntimeException();
- }
- t2 = System.currentTimeMillis();
- System.out.println("d3 = " + (t2 - t1));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement