criterion/
program.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
use std::fmt;
use std::io::BufReader;
use std::marker::PhantomData;
use std::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command, Stdio};
use std::time::{Duration, Instant};

use routine::Routine;
use DurationExt;

// A two-way channel to the standard streams of a child process
pub struct Program {
    buffer: String,
    stdin: ChildStdin,
    // NB Don't move the `stdin` field, because it must be dropped first
    _child: Child,
    stderr: ChildStderr,
    stdout: BufReader<ChildStdout>,
}

impl Program {
    pub fn spawn(cmd: &mut Command) -> Program {
        cmd.stderr(Stdio::piped());
        cmd.stdin(Stdio::piped());
        cmd.stdout(Stdio::piped());

        let mut child = match cmd.spawn() {
            Err(e) => panic!("`{:?}`: {}", cmd, e),
            Ok(child) => child,
        };

        Program {
            buffer: String::new(),
            stderr: child.stderr.take().unwrap(),
            stdin: child.stdin.take().unwrap(),
            stdout: BufReader::new(child.stdout.take().unwrap()),
            _child: child,
        }
    }

    pub fn send<T>(&mut self, line: T) -> &mut Program
    where
        T: fmt::Display,
    {
        use std::io::Write;

        match writeln!(&mut self.stdin, "{}", line) {
            Err(e) => panic!("`write into child stdin`: {}", e),
            Ok(_) => self,
        }
    }

    pub fn recv(&mut self) -> &str {
        use std::io::{BufRead, Read};

        self.buffer.clear();

        match self.stdout.read_line(&mut self.buffer) {
            Err(e) => {
                self.buffer.clear();

                match self.stderr.read_to_string(&mut self.buffer) {
                    Err(e) => {
                        panic!("`read from child stderr`: {}", e);
                    }
                    Ok(_) => {
                        println!("stderr:\n{}", self.buffer);
                    }
                }

                panic!("`read from child stdout`: {}", e);
            }
            Ok(_) => &self.buffer,
        }
    }

    fn bench(&mut self, iters: &[u64]) -> Vec<f64> {
        let mut n = 0;
        for iters in iters {
            self.send(iters);
            n += 1;
        }

        (0..n)
            .map(|_| {
                let msg = self.recv();
                let msg = msg.trim();

                let elapsed: u64 = msg.parse().expect("Couldn't parse program output");
                elapsed as f64
            })
            .collect()
    }

    fn warm_up(&mut self, how_long_ns: Duration) -> (u64, u64) {
        let mut iters = 1;

        let mut total_iters = 0;
        let start = Instant::now();
        loop {
            self.send(iters).recv();

            total_iters += iters;
            let elapsed = start.elapsed();
            if elapsed > how_long_ns {
                return (elapsed.to_nanos(), total_iters);
            }

            iters *= 2;
        }
    }
}

impl Routine<()> for Command {
    fn start(&mut self, _: &()) -> Option<Program> {
        Some(Program::spawn(self))
    }

    fn bench(&mut self, program: &mut Option<Program>, iters: &[u64], _: &()) -> Vec<f64> {
        let program = program.as_mut().unwrap();
        program.bench(iters)
    }

    fn warm_up(
        &mut self,
        program: &mut Option<Program>,
        how_long_ns: Duration,
        _: &(),
    ) -> (u64, u64) {
        let program = program.as_mut().unwrap();
        program.warm_up(how_long_ns)
    }
}

pub struct CommandFactory<F, T>
where
    F: FnMut(&T) -> Command + 'static,
{
    f: F,
    _phantom: PhantomData<T>,
}
impl<F, T> CommandFactory<F, T>
where
    F: FnMut(&T) -> Command + 'static,
{
    pub fn new(f: F) -> CommandFactory<F, T> {
        CommandFactory {
            f,
            _phantom: PhantomData,
        }
    }
}

impl<F, T> Routine<T> for CommandFactory<F, T>
where
    F: FnMut(&T) -> Command + 'static,
{
    fn start(&mut self, parameter: &T) -> Option<Program> {
        let mut command = (self.f)(parameter);
        Some(Program::spawn(&mut command))
    }

    fn bench(&mut self, program: &mut Option<Program>, iters: &[u64], _: &T) -> Vec<f64> {
        let program = program.as_mut().unwrap();
        program.bench(iters)
    }

    fn warm_up(
        &mut self,
        program: &mut Option<Program>,
        how_long_ns: Duration,
        _: &T,
    ) -> (u64, u64) {
        let program = program.as_mut().unwrap();
        program.warm_up(how_long_ns)
    }
}