ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/extra166y/ApplyDemo.java
Revision: 1.4
Committed: Tue Mar 15 19:47:04 2011 UTC (13 years, 2 months ago) by jsr166
Branch: MAIN
CVS Tags: release-1_7_0, HEAD
Changes since 1.3: +1 -1 lines
Log Message:
Update Creative Commons license URL in legal notices

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/publicdomain/zero/1.0/
5 */
6
7 import jsr166y.*;
8 import extra166y.*;
9 import java.util.*;
10 import java.util.concurrent.*;
11
12 public class ApplyDemo {
13 static final int NCPU = Runtime.getRuntime().availableProcessors();
14 /**
15 * Sequential version, for performance comparison
16 */
17 static <T> void seqApply(T[] array, Ops.Procedure<T> f) {
18 int n = array.length;
19 for (int i = 0; i < n; ++i)
20 f.op(array[i]);
21 }
22
23 /**
24 * A sample procedure to apply
25 */
26 static final class Proc implements Ops.Procedure<Rand> {
27 public void op(Rand x) {
28 for (int k = 0; k < (1 << 10); ++k)
29 x.next();
30 }
31 }
32
33 /** for time conversion */
34 static final long NPS = (1000L * 1000 * 1000);
35
36 public static void main(String[] args) throws Exception {
37 test();
38 test();
39 }
40
41 public static void test() throws Exception {
42 int n = 1 << 18;
43 Rand[] array = new Rand[n];
44 for (int i = 0; i < n; ++i)
45 array[i] = new Rand(i);
46 final Proc proc = new Proc();
47 long last, now;
48 double elapsed;
49 last = System.nanoTime();
50 for (int k = 0; k < 2; ++k) {
51 for (int j = 0; j < (1 << 3); ++j)
52 seqApply(array, proc);
53 now = System.nanoTime();
54 elapsed = (double)(now - last) / NPS;
55 last = now;
56 System.out.printf("seq: %7.3f\n", elapsed);
57 }
58 for (int i = 1; i <= NCPU; i <<= 1) {
59 ForkJoinPool fjp = new ForkJoinPool(i);
60 ParallelArray pa = ParallelArray.createUsingHandoff(array, fjp);
61 last = System.nanoTime();
62 for (int k = 0; k < 2; ++k) {
63 for (int j = 0; j < (1 << 3); ++j)
64 pa.apply(proc);
65 now = System.nanoTime();
66 elapsed = (double)(now - last) / NPS;
67 last = now;
68 System.out.printf("ps %2d: %7.3f\n", fjp.getParallelism(), elapsed);
69 }
70 fjp.shutdownNow();
71 fjp.awaitTermination(1, TimeUnit.SECONDS);
72 Thread.sleep(10);
73 }
74 int sum = 0;
75 for (int i = 0; i < array.length; ++i) sum += array[i].seed;
76 if (sum == 0)
77 System.out.print(" ");
78 }
79
80 /**
81 * Unsynchronized version of java.util.Random algorithm.
82 */
83 static final class Rand {
84 static final long multiplier = 0x5DEECE66DL;
85 static final long addend = 0xBL;
86 static final long mask = (1L << 48) - 1;
87 long seed;
88
89 Rand(long s) {
90 seed = s;
91 }
92 public int next() {
93 long nextseed = (seed * multiplier + addend) & mask;
94 seed = nextseed;
95 return ((int)(nextseed >>> 17)) & 0x7FFFFFFF;
96 }
97 }
98
99 }