rust/src/test/bench/shootout-pfib.rs

118 lines
2.5 KiB
Rust
Raw Normal View History

// -*- rust -*-
// xfail-pretty
/*
A parallel version of fibonacci numbers.
This version is meant mostly as a way of stressing and benchmarking
the task system. It supports a lot of command-line arguments to
control how it runs.
*/
use std;
import std::{time, getopts};
import io::writer_util;
import int::range;
import comm::port;
import comm::chan;
import comm::send;
import comm::recv;
import core::result;
import result::{ok, err};
2011-07-27 14:19:39 +02:00
fn fib(n: int) -> int {
2012-01-06 20:55:56 -08:00
fn pfib(c: chan<int>, n: int) {
2011-07-27 14:19:39 +02:00
if n == 0 {
2011-08-13 16:03:28 -07:00
send(c, 0);
} else if n <= 2 {
2011-08-13 16:03:28 -07:00
send(c, 1);
2011-07-27 14:19:39 +02:00
} else {
let p = port();
2012-01-06 20:55:56 -08:00
let ch = chan(p);
2012-06-30 16:19:07 -07:00
task::spawn(|| pfib(ch, n - 1) );
task::spawn(|| pfib(ch, n - 2) );
send(c, recv(p) + recv(p));
}
}
let p = port();
2012-01-06 20:55:56 -08:00
let ch = chan(p);
2012-06-30 16:19:07 -07:00
let t = task::spawn(|| pfib(ch, n) );
2012-08-01 17:30:05 -07:00
return recv(p);
}
2011-07-27 14:19:39 +02:00
type config = {stress: bool};
2011-07-07 17:28:20 -07:00
fn parse_opts(argv: ~[~str]) -> config {
let opts = ~[getopts::optflag(~"stress")];
2011-07-07 17:28:20 -07:00
2011-08-15 16:38:23 -07:00
let opt_args = vec::slice(argv, 1u, vec::len(argv));
2011-07-07 17:28:20 -07:00
2011-07-27 14:19:39 +02:00
2011-08-11 23:27:32 -07:00
alt getopts::getopts(opt_args, opts) {
2012-08-01 17:30:05 -07:00
ok(m) { return {stress: getopts::opt_present(m, ~"stress")} }
err(_) { fail; }
2011-07-07 17:28:20 -07:00
}
}
2011-10-20 20:34:04 -07:00
fn stress_task(&&id: int) {
let mut i = 0;
loop {
2011-07-27 14:19:39 +02:00
let n = 15;
assert (fib(n) == fib(n));
2011-07-07 17:28:20 -07:00
i += 1;
error!{"%d: Completed %d iterations", id, i};
2011-07-07 17:28:20 -07:00
}
}
2011-07-27 14:19:39 +02:00
fn stress(num_tasks: int) {
let mut results = ~[];
2012-06-30 16:19:07 -07:00
for range(0, num_tasks) |i| {
do task::task().future_result(|-r| {
results += ~[r];
}).spawn {
stress_task(i);
}
}
2012-06-30 16:19:07 -07:00
for results.each |r| { future::get(r); }
2011-07-07 17:28:20 -07:00
}
fn main(args: ~[~str]) {
let args = if os::getenv(~"RUST_BENCH").is_some() {
~[~"", ~"20"]
} else if args.len() <= 1u {
~[~"", ~"8"]
2011-07-27 14:19:39 +02:00
} else {
args
};
2011-07-27 14:19:39 +02:00
let opts = parse_opts(args);
if opts.stress {
stress(2);
} else {
let max = option::get(uint::parse_buf(str::bytes(args[1]),
10u)) as int;
2011-07-27 14:19:39 +02:00
let num_trials = 10;
let out = io::stdout();
2012-06-30 16:19:07 -07:00
for range(1, max + 1) |n| {
for range(0, num_trials) |i| {
let start = time::precise_time_ns();
let fibn = fib(n);
let stop = time::precise_time_ns();
let elapsed = stop - start;
out.write_line(fmt!{"%d\t%d\t%s", n, fibn,
u64::str(elapsed)});
}
}
}
}