|
| 1 | +// -*- rust -*- |
| 2 | + |
| 3 | +/* |
| 4 | + A parallel version of fibonacci numbers. |
| 5 | +
|
| 6 | + This version is meant mostly as a way of stressing and benchmarking |
| 7 | + the task system. It supports a lot of command-line arguments to |
| 8 | + control how it runs. |
| 9 | +
|
| 10 | +*/ |
| 11 | + |
| 12 | +use std; |
| 13 | + |
| 14 | +import std::vec; |
| 15 | +import std::uint; |
| 16 | +import std::time; |
| 17 | +import std::str; |
| 18 | +import std::int::range; |
| 19 | +import std::io; |
| 20 | + |
| 21 | +fn recv[T](&port[T] p) -> T { |
| 22 | + let T x; |
| 23 | + p |> x; |
| 24 | + ret x; |
| 25 | +} |
| 26 | + |
| 27 | +fn fib(int n) -> int { |
| 28 | + fn pfib(chan[int] c, int n) { |
| 29 | + if (n == 0) { |
| 30 | + c <| 0; |
| 31 | + } |
| 32 | + else if (n <= 2) { |
| 33 | + c <| 1; |
| 34 | + } |
| 35 | + else { |
| 36 | + let port[int] p = port(); |
| 37 | + |
| 38 | + auto t1 = spawn pfib(chan(p), n - 1); |
| 39 | + auto t2 = spawn pfib(chan(p), n - 2); |
| 40 | + |
| 41 | + c <| recv(p) + recv(p); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + let port[int] p = port(); |
| 46 | + auto t = spawn pfib(chan(p), n); |
| 47 | + ret recv(p); |
| 48 | +} |
| 49 | + |
| 50 | +fn main(vec[str] argv) { |
| 51 | + if(vec::len(argv) == 1u) { |
| 52 | + assert (fib(8) == 21); |
| 53 | + assert (fib(15) == 610); |
| 54 | + log fib(8); |
| 55 | + log fib(15); |
| 56 | + } |
| 57 | + else { |
| 58 | + // Interactive mode! Wooo!!!! |
| 59 | + |
| 60 | + auto max = uint::parse_buf(str::bytes(argv.(1)), 10u) as int; |
| 61 | + |
| 62 | + auto num_trials = 10; |
| 63 | + |
| 64 | + auto out = io::stdout(); |
| 65 | + |
| 66 | + for each(int n in range(1, max + 1)) { |
| 67 | + for each(int i in range(0, num_trials)) { |
| 68 | + auto start = time::precise_time_ns(); |
| 69 | + auto fibn = fib(n); |
| 70 | + auto stop = time::precise_time_ns(); |
| 71 | + |
| 72 | + auto elapsed = (stop - start) as int; |
| 73 | + |
| 74 | + out.write_line(#fmt("%d\t%d\t%d", n, fibn, elapsed)); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + } |
| 79 | +} |
0 commit comments