]> git.lizzy.rs Git - rust.git/blob - src/test/bench/rt-messaging-ping-pong.rs
Auto merge of #28827 - thepowersgang:unsafe-const-fn-2, r=Aatch
[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::env;
22 use std::thread;
23
24 // This is a simple bench that creates M pairs of threads. These
25 // threads ping-pong back and forth over a pair of streams. This is a
26 // canonical message-passing benchmark as it heavily strains message
27 // passing and almost nothing else.
28
29 fn ping_pong_bench(n: usize, m: usize) {
30
31     // Create pairs of threads that pingpong back and forth.
32     fn run_pair(n: usize) {
33         // Create a channel: A->B
34         let (atx, arx) = channel();
35         // Create a channel: B->A
36         let (btx, brx) = channel();
37
38         let guard_a = thread::spawn(move|| {
39             let (tx, rx) = (atx, brx);
40             for _ in 0..n {
41                 tx.send(()).unwrap();
42                 rx.recv().unwrap();
43             }
44         });
45
46         let guard_b = thread::spawn(move|| {
47             let (tx, rx) = (btx, arx);
48             for _ in 0..n {
49                 rx.recv().unwrap();
50                 tx.send(()).unwrap();
51             }
52         });
53
54         guard_a.join().ok();
55         guard_b.join().ok();
56     }
57
58     for _ in 0..m {
59         run_pair(n)
60     }
61 }
62
63
64
65 fn main() {
66     let mut args = env::args();
67     let (n, m) = if args.len() == 3 {
68         let n = args.nth(1).unwrap().parse::<usize>().unwrap();
69         let m = args.next().unwrap().parse::<usize>().unwrap();
70         (n, m)
71     } else {
72         (10000, 4)
73     };
74
75     ping_pong_bench(n, m);
76
77 }