OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 library dart.pkg.isolate.sample.runners; |
| 6 |
| 7 import "package:isolate/loadbalancer.dart"; |
| 8 import "package:isolate/isolaterunner.dart"; |
| 9 import "dart:async" show Future, Completer; |
| 10 |
| 11 |
| 12 void main() { |
| 13 int N = 44; |
| 14 var sw = new Stopwatch()..start(); |
| 15 // Compute fib up to 42 with 4 isolates. |
| 16 parfib(N, 4).then((v1) { |
| 17 var t1 = sw.elapsedMilliseconds; |
| 18 sw.stop(); |
| 19 sw.reset(); |
| 20 print("fib#4(${N}) = ${v1[N]}, ms: $t1"); |
| 21 sw.start(); |
| 22 // Then compute fib up to 42 with 2 isolates. |
| 23 parfib(N, 2).then((v2) { |
| 24 var t2 = sw.elapsedMilliseconds; |
| 25 sw.stop(); |
| 26 print("fib#2(${N}) = ${v2[N]}, ms: $t2"); |
| 27 }); |
| 28 }); |
| 29 } |
| 30 |
| 31 // Compute fibonnacci 1..limit |
| 32 Future<List<int>> parfib(int limit, int parallelity) { |
| 33 return LoadBalancer.create(parallelity, IsolateRunner.spawn).then( |
| 34 (LoadBalancer pool) { |
| 35 List<Future> fibs = new List(limit + 1); |
| 36 // Schedule all calls with exact load value and the heaviest task |
| 37 // assigned first. |
| 38 schedule(a, b, i) { |
| 39 if (i < limit) { |
| 40 schedule(a + b, a, i + 1); |
| 41 } |
| 42 fibs[i] = pool.run(fib, i, load: a); |
| 43 } |
| 44 schedule(0, 1, 0); |
| 45 // And wait for them all to complete. |
| 46 return Future.wait(fibs).whenComplete(pool.close); |
| 47 }); |
| 48 } |
| 49 |
| 50 int computeFib(n) { |
| 51 int result = fib(n); |
| 52 return result; |
| 53 } |
| 54 |
| 55 int fib(n) { |
| 56 if (n < 2) return n; |
| 57 return fib(n - 1) + fib(n - 2); |
| 58 } |
OLD | NEW |