/Users/lyon/j4p/src/bookExamples/ch05ControlStructs/LoopInterchange.java
|
1 package bookExamples.ch05ControlStructs;
2
3 import utils.Timer;
4
5 public class LoopInterchange {
6 int jmax = 700;
7 int imax = 700;
8 int i, j;
9
10 float x[][] = new float[imax][jmax];
11 float y[] = new float[imax * jmax];
12
13 public void test() {
14 double t1,t2,t3,speedup;
15
16 t1 = testLoop1();
17 System.out.println("loop1:" + t1 + " seconds");
18 t2 = testLoop2();
19 System.out.println("loop2:" + t2 + " seconds");
20 t3 = testLoop3();
21 System.out.println("loop3:" + t3 + " seconds");
22 }
23
24 double testLoop3() {
25 Timer t = new Timer();
26 t.start();
27 for (j = 0; j < jmax; j++)
28 for (i = 0; i < imax; i++)
29 x[i][j] *= 2;
30 t.stop();
31 System.out.println("first index faster");
32 return t.getTime();
33 }
34
35 double testLoop1() {
36 Timer t = new Timer();
37 t.start();
38
39 for (i = 0; i < imax; i++)
40 for (j = 0; j < jmax; j++)
41 y[j + i * imax] *= 2;
42 t.stop();
43 System.out.println("multiply access");
44 return t.getTime();
45 }
46
47 double testLoop2() {
48 Timer t = new Timer();
49 t.start();
50 for (i = 0; i < imax; i++)
51 for (j = 0; j < jmax; j++)
52 x[i][j] *= 2;
53 t.stop();
54 System.out.println("second index faster");
55 return t.getTime();
56 }
57
58 public static void main(String args[]) {
59 LoopInterchange li = new LoopInterchange();
60 for (int i = 0; i < 10; i++)
61 li.test();
62 }
63 }