]> git.lizzy.rs Git - rust.git/blob - src/test/bench/rt-messaging-ping-pong.rs
Merge pull request #20510 from tshepang/patch-6
[rust.git] / src / test / bench / rt-messaging-ping-pong.rs
1 // Copyright 2014 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.
4 //
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.
10
11 // file at the top-level directory of this distribution and at
12 // http://rust-lang.org/COPYRIGHT.
13 //
14 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
15 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
16 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
17 // option. This file may not be copied, modified, or distributed
18 // except according to those terms.
19
20 use std::sync::mpsc::channel;
21 use std::os;
22 use std::thread::Thread;
23 use std::uint;
24
25 // This is a simple bench that creates M pairs of tasks. These
26 // tasks ping-pong back and forth over a pair of streams. This is a
27 // canonical message-passing benchmark as it heavily strains message
28 // passing and almost nothing else.
29
30 fn ping_pong_bench(n: uint, m: uint) {
31
32     // Create pairs of tasks that pingpong back and forth.
33     fn run_pair(n: uint) {
34         // Create a stream A->B
35         let (atx, arx) = channel::<()>();
36         // Create a stream B->A
37         let (btx, brx) = channel::<()>();
38
39         Thread::spawn(move|| {
40             let (tx, rx) = (atx, brx);
41             for _ in range(0, n) {
42                 tx.send(());
43                 rx.recv();
44             }
45         }).detach();
46
47         Thread::spawn(move|| {
48             let (tx, rx) = (btx, arx);
49             for _ in range(0, n) {
50                 rx.recv();
51                 tx.send(());
52             }
53         }).detach();
54     }
55
56     for _ in range(0, m) {
57         run_pair(n)
58     }
59 }
60
61
62
63 fn main() {
64
65     let args = os::args();
66     let args = args.as_slice();
67     let n = if args.len() == 3 {
68         args[1].parse::<uint>().unwrap()
69     } else {
70         10000
71     };
72
73     let m = if args.len() == 3 {
74         args[2].parse::<uint>().unwrap()
75     } else {
76         4
77     };
78
79     ping_pong_bench(n, m);
80
81 }