--- jsr166/src/test/loops/DynamicLeftSpineFib.java 2009/10/29 23:14:43 1.3 +++ jsr166/src/test/loops/DynamicLeftSpineFib.java 2009/11/14 20:58:11 1.7 @@ -1,4 +1,9 @@ -//import jsr166y.*; +/* + * Written by Doug Lea with assistance from members of JCP JSR-166 + * Expert Group and released to the public domain, as explained at + * http://creativecommons.org/licenses/publicdomain + */ + import java.util.*; import java.util.concurrent.*; @@ -6,7 +11,7 @@ public final class DynamicLeftSpineFib e // Performance-tuning constant: static long lastStealCount; - + public static void main(String[] args) throws Exception { int procs = 0; int num = 43; @@ -17,11 +22,11 @@ public final class DynamicLeftSpineFib e num = Integer.parseInt(args[1]); } catch (Exception e) { - System.out.println("Usage: java DynamicLeftSpineFib []"); + System.out.println("Usage: java DynamicLeftSpineFib []"); return; } - + for (int reps = 0; reps < 2; ++reps) { ForkJoinPool g = procs == 0? new ForkJoinPool() : new ForkJoinPool(procs); @@ -42,7 +47,7 @@ public final class DynamicLeftSpineFib e long time = System.currentTimeMillis() - start; double secs = ((double)time) / 1000.0; long result = f.getAnswer(); - System.out.print("DynamicLeftSpineFib " + num + " = " + result); + System.out.print("DLSFib " + num + " = " + result); System.out.printf("\tTime: %7.3f", secs); long sc = g.getStealCount(); long ns = sc - lastStealCount; @@ -57,8 +62,8 @@ public final class DynamicLeftSpineFib e int number; DynamicLeftSpineFib next; - DynamicLeftSpineFib(int n, DynamicLeftSpineFib nxt) { - number = n; next = nxt; + DynamicLeftSpineFib(int n, DynamicLeftSpineFib nxt) { + number = n; next = nxt; } int getAnswer() { @@ -68,12 +73,22 @@ public final class DynamicLeftSpineFib e public final void compute() { int n = number; if (n > 1) { + int r = 0; DynamicLeftSpineFib rt = null; - while (n > 1 && getSurplusQueuedTaskCount() <= 3) { - (rt = new DynamicLeftSpineFib(n - 2, rt)).fork(); + while (getSurplusQueuedTaskCount() <= 3) { + int m = n - 2; n -= 1; + if (m <= 1) { + r += m; + if (n > 1) { + r += n - 2; + n -= 1; + } + break; + } + (rt = new DynamicLeftSpineFib(m, rt)).fork(); } - int r = seqFib(n); + r += seqFib(n); while (rt != null) { if (rt.tryUnfork()) rt.compute(); else rt.helpJoin(); r += rt.number; @@ -85,10 +100,11 @@ public final class DynamicLeftSpineFib e // Sequential version for arguments less than threshold static int seqFib(int n) { - if (n <= 1) + if (n <= 1) return n; - else + else return seqFib(n-1) + seqFib(n-2); } - + } +