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/licenses/publicdomain |
5 |
*/ |
6 |
|
7 |
//import jsr166y.*; |
8 |
import java.util.*; |
9 |
import java.util.concurrent.*; |
10 |
|
11 |
public final class DynamicLeftSpineFib extends RecursiveAction { |
12 |
|
13 |
// Performance-tuning constant: |
14 |
static long lastStealCount; |
15 |
|
16 |
public static void main(String[] args) throws Exception { |
17 |
int procs = 0; |
18 |
int num = 43; |
19 |
try { |
20 |
if (args.length > 0) |
21 |
procs = Integer.parseInt(args[0]); |
22 |
if (args.length > 1) |
23 |
num = Integer.parseInt(args[1]); |
24 |
} |
25 |
catch (Exception e) { |
26 |
System.out.println("Usage: java DynamicLeftSpineFib <threads> <number> [<sequentialThreshold>]"); |
27 |
return; |
28 |
} |
29 |
|
30 |
|
31 |
for (int reps = 0; reps < 2; ++reps) { |
32 |
ForkJoinPool g = (procs == 0) ? |
33 |
new ForkJoinPool() : |
34 |
new ForkJoinPool(procs); |
35 |
lastStealCount = g.getStealCount(); |
36 |
for (int i = 0; i < 10; ++i) { |
37 |
test(g, num); |
38 |
} |
39 |
System.out.println(g); |
40 |
g.shutdown(); |
41 |
} |
42 |
} |
43 |
|
44 |
static void test(ForkJoinPool g, int num) throws Exception { |
45 |
int ps = g.getParallelism(); |
46 |
long start = System.currentTimeMillis(); |
47 |
DynamicLeftSpineFib f = new DynamicLeftSpineFib(num, null); |
48 |
g.invoke(f); |
49 |
long time = System.currentTimeMillis() - start; |
50 |
double secs = (double) time / 1000.0; |
51 |
long result = f.getAnswer(); |
52 |
System.out.print("DynamicLeftSpineFib " + num + " = " + result); |
53 |
System.out.printf("\tTime: %7.3f", secs); |
54 |
long sc = g.getStealCount(); |
55 |
long ns = sc - lastStealCount; |
56 |
lastStealCount = sc; |
57 |
System.out.printf(" Steals/t: %5d", ns/ps); |
58 |
System.out.printf(" Workers: %8d", g.getPoolSize()); |
59 |
System.out.println(); |
60 |
} |
61 |
|
62 |
|
63 |
// Initialized with argument; replaced with result |
64 |
int number; |
65 |
DynamicLeftSpineFib next; |
66 |
|
67 |
DynamicLeftSpineFib(int n, DynamicLeftSpineFib nxt) { |
68 |
number = n; next = nxt; |
69 |
} |
70 |
|
71 |
int getAnswer() { |
72 |
return number; |
73 |
} |
74 |
|
75 |
public final void compute() { |
76 |
int n = number; |
77 |
if (n > 1) { |
78 |
DynamicLeftSpineFib rt = null; |
79 |
while (n > 1 && getSurplusQueuedTaskCount() <= 3) { |
80 |
(rt = new DynamicLeftSpineFib(n - 2, rt)).fork(); |
81 |
n -= 1; |
82 |
} |
83 |
int r = seqFib(n); |
84 |
while (rt != null) { |
85 |
if (rt.tryUnfork()) rt.compute(); else rt.helpJoin(); |
86 |
r += rt.number; |
87 |
rt = rt.next; |
88 |
} |
89 |
number = r; |
90 |
} |
91 |
} |
92 |
|
93 |
// Sequential version for arguments less than threshold |
94 |
static int seqFib(int n) { |
95 |
if (n <= 1) |
96 |
return n; |
97 |
else |
98 |
return seqFib(n-1) + seqFib(n-2); |
99 |
} |
100 |
|
101 |
} |