]> git.proxmox.com Git - rustc.git/blob - vendor/rustc-rayon/examples/cpu_monitor.rs
New upstream version 1.35.0+dfsg1
[rustc.git] / vendor / rustc-rayon / examples / cpu_monitor.rs
1 extern crate docopt;
2 extern crate rayon;
3 #[macro_use]
4 extern crate serde_derive;
5 extern crate serde;
6
7 use docopt::Docopt;
8 use std::io;
9 use std::process;
10
11 const USAGE: &'static str = "
12 Usage: cpu_monitor [options] <scenario>
13 cpu_monitor --help
14
15 A test for monitoring how much CPU usage Rayon consumes under various
16 scenarios. This test is intended to be executed interactively, like so:
17
18 cargo run --example cpu_monitor -- tasks_ended
19
20 The list of scenarios you can try are as follows:
21
22 - tasks_ended: after all tasks have finished, go to sleep
23 - task_stall_root: a root task stalls for a very long time
24 - task_stall_scope: a task in a scope stalls for a very long time
25
26 Options:
27 -h, --help Show this message.
28 -d N, --depth N Control how hard the dummy task works [default: 27]
29 ";
30
31 #[derive(Deserialize)]
32 pub struct Args {
33 arg_scenario: String,
34 flag_depth: usize,
35 }
36
37 fn main() {
38 let args: &Args = &Docopt::new(USAGE)
39 .and_then(|d| d.deserialize())
40 .unwrap_or_else(|e| e.exit());
41
42 match &args.arg_scenario[..] {
43 "tasks_ended" => tasks_ended(args),
44 "task_stall_root" => task_stall_root(args),
45 "task_stall_scope" => task_stall_scope(args),
46 _ => {
47 println!("unknown scenario: `{}`", args.arg_scenario);
48 println!("try --help");
49 process::exit(1);
50 }
51 }
52 }
53
54 fn wait_for_user() {
55 let mut input = String::new();
56 io::stdin().read_line(&mut input).unwrap();
57 }
58
59 fn task(args: &Args) {
60 fn join_recursively(n: usize) {
61 if n == 0 {
62 return;
63 }
64 rayon::join(|| join_recursively(n - 1), || join_recursively(n - 1));
65 }
66
67 println!("Starting heavy work at depth {}...wait.", args.flag_depth);
68 join_recursively(args.flag_depth);
69 println!("Heavy work done; check top. You should see CPU usage drop to zero soon.");
70 println!("Press <enter> to quit...");
71 }
72
73 fn tasks_ended(args: &Args) {
74 task(args);
75 wait_for_user();
76 }
77
78 fn task_stall_root(args: &Args) {
79 rayon::join(|| task(args), || wait_for_user());
80 }
81
82 fn task_stall_scope(args: &Args) {
83 rayon::scope(|scope| {
84 scope.spawn(move |_| task(args));
85 scope.spawn(move |_| wait_for_user());
86 });
87 }