1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 A parallel version of fibonacci numbers.
15 This version is meant mostly as a way of stressing and benchmarking
16 the task system. It supports a lot of old command-line arguments to
25 use std::result::{Ok, Err};
27 use std::task::TaskBuilder;
30 fn fib(n: int) -> int {
31 fn pfib(tx: &Sender<int>, n: int) {
37 let (tx1, rx) = channel();
38 let tx2 = tx1.clone();
39 task::spawn(proc() pfib(&tx2, n - 1));
40 let tx2 = tx1.clone();
41 task::spawn(proc() pfib(&tx2, n - 2));
42 tx.send(rx.recv() + rx.recv());
46 let (tx, rx) = channel();
47 spawn(proc() pfib(&tx, n) );
55 fn parse_opts(argv: Vec<~str> ) -> Config {
56 let opts = vec!(getopts::optflag("", "stress", ""));
58 let opt_args = argv.slice(1, argv.len());
60 match getopts::getopts(opt_args, opts.as_slice()) {
62 return Config {stress: m.opt_present("stress")}
64 Err(_) => { fail!(); }
68 fn stress_task(id: int) {
72 assert_eq!(fib(n), fib(n));
74 println!("{}: Completed {} iterations", id, i);
78 fn stress(num_tasks: int) {
79 let mut results = Vec::new();
80 for i in range(0, num_tasks) {
81 let mut builder = TaskBuilder::new();
82 results.push(builder.future_result());
83 builder.spawn(proc() {
87 for r in results.iter() {
93 let args = os::args();
94 let args = if os::getenv("RUST_BENCH").is_some() {
95 vec!("".to_owned(), "20".to_owned())
96 } else if args.len() <= 1u {
97 vec!("".to_owned(), "8".to_owned())
99 args.move_iter().collect()
102 let opts = parse_opts(args.clone());
107 let max = uint::parse_bytes(args.get(1).as_bytes(), 10u).unwrap() as
112 for n in range(1, max + 1) {
113 for _ in range(0, num_trials) {
114 let start = time::precise_time_ns();
116 let stop = time::precise_time_ns();
118 let elapsed = stop - start;
120 println!("{}\t{}\t{}", n, fibn, elapsed.to_str());