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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
use stats;
use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use std::iter::repeat;
use std::path::PathBuf;
use std::process;
use std::sync::atomic::{self, AtomicBool};
use std::sync::Arc;
use std::time::Instant;
use ctrlc;
use rand::{thread_rng, ChaChaRng, SeedableRng, Rng};
#[derive(Copy, Clone)]
pub struct BenchName(pub &'static str);
impl BenchName {
fn padded(&self, column_count: usize) -> String {
let mut name = self.0.to_string();
let fill = column_count.saturating_sub(name.len());
let pad = repeat(" ").take(fill).collect::<String>();
name.push_str(&pad);
name
}
}
pub type BenchRng = ChaChaRng;
pub type BenchFn = fn(&mut CtRunner, &mut BenchRng);
#[derive(Clone)]
enum BenchEvent {
BContStart,
BBegin(Vec<BenchName>),
BWait(BenchName),
BResult(MonitorMsg),
BSeed(Vec<u32>, BenchName),
}
type MonitorMsg = (BenchName, stats::CtSummary);
struct CtBencher {
samples: (Vec<u64>, Vec<u64>),
ctx: Option<stats::CtCtx>,
file_out: Option<File>,
rng: BenchRng,
}
impl CtBencher {
pub fn new_unseeded() -> CtBencher {
CtBencher {
samples: (Vec::new(), Vec::new()),
ctx: None,
file_out: None,
rng: BenchRng::new_unseeded(),
}
}
fn go(&mut self, f: &BenchFn) -> stats::CtSummary {
let mut runner = CtRunner::default();
f(&mut runner, &mut self.rng);
self.samples = runner.runtimes;
let old_self = ::std::mem::replace(self, CtBencher::new_unseeded());
let (summ, new_ctx) = stats::update_ct_stats(old_self.ctx, &old_self.samples);
self.samples = old_self.samples;
self.file_out = old_self.file_out;
self.ctx = Some(new_ctx);
self.rng = old_self.rng;
summ
}
fn rand_seed() -> Vec<u32> {
let mut rng = thread_rng();
let mut seed = vec![0u32; 4];
seed[0] = rng.gen();
seed[1] = rng.gen();
seed[2] = rng.gen();
seed[3] = rng.gen();
seed
}
pub fn seed_with(&mut self, seed: &[u32]) {
self.rng = BenchRng::from_seed(seed);
}
fn clear_data(&mut self) {
self.samples = (Vec::new(), Vec::new());
self.ctx = None;
}
}
pub struct BenchMetadata {
pub name: BenchName,
pub seed: Option<Vec<u32>>,
pub benchfn: BenchFn,
}
#[derive(Default)]
pub struct BenchOpts {
pub continuous: bool,
pub filter: Option<String>,
pub file_out: Option<PathBuf>,
}
#[derive(Default)]
struct ConsoleBenchState {
max_name_len: usize,
}
impl ConsoleBenchState {
fn write_plain(&mut self, s: &str) -> io::Result<()> {
let mut stdout = io::stdout();
stdout.write_all(s.as_bytes())?;
stdout.flush()
}
fn write_bench_start(&mut self, name: &BenchName) -> io::Result<()> {
let name = name.padded(self.max_name_len);
self.write_plain(&format!("bench {} ... ", name))
}
fn write_seed(&mut self, seed: &[u32], name: &BenchName) -> io::Result<()> {
let name = name.padded(self.max_name_len);
self.write_plain(&format!("bench {} seeded with [0x{:x}, 0x{:x}, 0x{:x}, 0x{:x}]\n",
name, seed[0], seed[1], seed[2], seed[3]))
}
fn write_run_start(&mut self, len: usize) -> io::Result<()> {
let noun = if len != 1 {
"benches"
} else {
"bench"
};
self.write_plain(&format!("\nrunning {} {}\n", len, noun))
}
fn write_continuous_start(&mut self) -> io::Result<()> {
self.write_plain("running 1 benchmark continuously\n")
}
fn write_result(&mut self, summ: &stats::CtSummary) -> io::Result<()> {
self.write_plain(&format!(": {}\n", summ.fmt()))
}
fn write_run_finish(&mut self) -> io::Result<()> {
self.write_plain("\ndudect benches complete\n\n")
}
}
pub fn run_benches_console(opts: BenchOpts, benches: Vec<BenchMetadata>) -> io::Result<()> {
fn callback(event: &BenchEvent, st: &mut ConsoleBenchState) -> io::Result<()> {
match (*event).clone() {
BenchEvent::BContStart => st.write_continuous_start(),
BenchEvent::BBegin(ref filtered_benches) => st.write_run_start(filtered_benches.len()),
BenchEvent::BWait(ref b) => st.write_bench_start(b),
BenchEvent::BResult(msg) => {
let (_, summ) = msg;
st.write_result(&summ)
},
BenchEvent::BSeed(ref seed, ref name) => st.write_seed(&*seed, name),
}
}
let mut st = ConsoleBenchState::default();
st.max_name_len = benches.iter().map(|t| t.name.0.len()).max().unwrap_or(0);
try!(run_benches(&opts, benches, |x| callback(&x, &mut st)));
st.write_run_finish()
}
fn setup_kill_bit() -> Arc<AtomicBool> {
let x = Arc::new(AtomicBool::new(false));
let y = x.clone();
ctrlc::set_handler(move || { y.store(true, atomic::Ordering::SeqCst) })
.expect("Error setting Ctrl-C handler");
x
}
fn run_benches<F>(opts: &BenchOpts, benches: Vec<BenchMetadata>, mut callback: F)
-> io::Result<()> where F: FnMut(BenchEvent) -> io::Result<()> {
use self::BenchEvent::*;
let filter = &opts.filter;
let filtered_benches = filter_benches(filter, benches);
let filtered_names = filtered_benches.iter().map(|b| b.name.clone()).collect();
let mut file_out = opts.file_out.as_ref().map(|filename| {
OpenOptions::new().write(true)
.truncate(true)
.create(true)
.open(filename)
.expect(&*format!("Could not open file '{:?}' for writing", filename))
});
file_out.as_mut().map(|f| f.write(b"benchname,class,runtime")
.expect("Error writing CSV header to file"));
let mut cb: CtBencher = {
let mut d = CtBencher::new_unseeded();
d.file_out = file_out;
d
};
if opts.continuous {
callback(BContStart)?;
if filtered_benches.len() == 0 {
match filter {
&Some(ref f) => panic!("No benchmark matching '{}' was found", f),
&None => return Ok(()),
}
}
let kill_bit = setup_kill_bit();
let mut filtered_benches = filtered_benches;
let bench = filtered_benches.remove(0);
let seed = bench.seed.unwrap_or_else(|| CtBencher::rand_seed());
cb.seed_with(&*seed);
callback(BSeed(seed, bench.name))?;
loop {
callback(BWait(bench.name))?;
let msg = run_bench_with_bencher(&bench.name, &bench.benchfn, &mut cb);
callback(BResult(msg))?;
if kill_bit.load(atomic::Ordering::SeqCst) {
process::exit(0);
}
}
}
else {
callback(BBegin(filtered_names))?;
for bench in filtered_benches {
cb.clear_data();
let seed = bench.seed.unwrap_or_else(|| CtBencher::rand_seed());
cb.seed_with(&*seed);
callback(BSeed(seed, bench.name))?;
callback(BWait(bench.name))?;
let msg = run_bench_with_bencher(&bench.name, &bench.benchfn, &mut cb);
callback(BResult(msg))?;
}
Ok(())
}
}
fn run_bench_with_bencher(name: &BenchName, benchfn: &BenchFn, cb: &mut CtBencher) -> MonitorMsg {
let summ = cb.go(benchfn);
let samples_iter = cb.samples.0.iter().zip(cb.samples.1.iter());
cb.file_out.as_mut().map(|mut f| {
for (x, y) in samples_iter {
write!(f, "\n{},0,{}", name.0, x).expect("Error writing data to file");
write!(f, "\n{},0,{}", name.0, y).expect("Error writing data to file");
}
});
(name.clone(), summ)
}
fn filter_benches(filter: &Option<String>, bs: Vec<BenchMetadata>) -> Vec<BenchMetadata> {
let mut filtered = bs;
filtered = match filter {
&None => filtered,
&Some(ref filter) => {
filtered.into_iter()
.filter(|b| b.name.0.contains(&filter[..]))
.collect()
}
};
filtered.sort_by(|b1, b2| b1.name.0.cmp(&b2.name.0));
filtered
}
fn black_box<T>(dummy: T) -> T {
unsafe {
let ret = ::std::ptr::read_volatile(&dummy);
::std::mem::forget(dummy);
ret
}
}
#[derive(Copy, Clone)]
pub enum Class {
Left, Right
}
#[derive(Default)]
pub struct CtRunner {
runtimes: (Vec<u64>, Vec<u64>),
}
impl CtRunner {
pub fn run_one<T, F>(&mut self, class: Class, f: F) where F: Fn() -> T {
let start = Instant::now();
black_box(f());
let end = Instant::now();
let runtime = {
let dur = end.duration_since(start);
dur.as_secs() * 1_000_000_000 + (dur.subsec_nanos() as u64)
};
match class {
Class::Left => self.runtimes.0.push(runtime),
Class::Right => self.runtimes.1.push(runtime),
}
}
}