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
23 use std::sync::mpsc::{channel, Sender};
25 use std::result::Result::{Ok, Err};
26 use std::thread::Thread;
27 use std::time::Duration;
29 fn fib(n: int) -> int {
30 fn pfib(tx: &Sender<int>, n: int) {
36 let (tx1, rx) = channel();
37 let tx2 = tx1.clone();
38 Thread::spawn(move|| pfib(&tx2, n - 1)).detach();
39 let tx2 = tx1.clone();
40 Thread::spawn(move|| pfib(&tx2, n - 2)).detach();
41 tx.send(rx.recv().unwrap() + rx.recv().unwrap());
45 let (tx, rx) = channel();
46 Thread::spawn(move|| pfib(&tx, n) ).detach();
54 fn parse_opts(argv: Vec<String> ) -> Config {
55 let opts = vec!(getopts::optflag("", "stress", ""));
57 let argv = argv.iter().map(|x| x.to_string()).collect::<Vec<_>>();
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(_) => { panic!(); }
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 results.push(Thread::spawn(move|| {
85 for r in results.into_iter() {
91 let args = os::args();
92 let args = if os::getenv("RUST_BENCH").is_some() {
93 vec!("".to_string(), "20".to_string())
94 } else if args.len() <= 1u {
95 vec!("".to_string(), "8".to_string())
97 args.into_iter().map(|x| x.to_string()).collect()
100 let opts = parse_opts(args.clone());
105 let max = args[1].parse::<int>().unwrap();
109 for n in range(1, max + 1) {
110 for _ in range(0u, num_trials) {
112 let dur = Duration::span(|| fibn = Some(fib(n)));
113 let fibn = fibn.unwrap();
115 println!("{}\t{}\t{}", n, fibn, dur);