~mht/cmr

ref: 7c61834a0fa0c6eeb4f4164f68c479d6e67d3118 cmr/benchmarks/src/main.rs -rw-r--r-- 13.7 KiB
7c61834a — Martin Hafskjold Thoresen Write comments. 4 years ago
                                                                                
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
#![allow(dead_code)]
#![feature(nll)]

extern crate rand;
extern crate trench;
extern crate cmr;
extern crate cmr_data_structures;
extern crate lapp;

use std::time::Duration;

use rand::Rng;
use cmr_data_structures::hashmap::HashMap;
use cmr_data_structures::msqueue::MsQueue as Queue;
use cmr_data_structures::stack::Stack;

const N: u64 = 10_000;

macro_rules! S {
    ($e:expr) => {
        (stringify!($e), $e as fn(usize))
    }
}

fn duration() -> Duration {
    Duration::new(1, 0)
}

fn fmt_thousands_sep(mut n: u64) -> String {
    let sep = ',';
    use std::fmt::Write;
    let mut output = String::new();
    let mut trailing = false;
    for &pow in &[15, 12, 9, 6, 3, 0] {
        let base = 10u64.pow(pow);
        if pow == 0 || trailing || n / base != 0 {
            if !trailing {
                output.write_fmt(format_args!("{}", n / base)).unwrap();
            } else {
                output.write_fmt(format_args!("{:03}", n / base)).unwrap();
            }
            if pow != 0 {
                output.push(sep);
            }
            trailing = true;
        }
        n %= base;
    }

    output
}

/// Thread local state for genrating random numbers. This is useful for the hashmap benchmarks
/// since we can generate keys before starting the benchmark, and then have the state keep track
/// over which numbers we've used up.
#[derive(Clone)]
struct RandomSource<T>(std::iter::Cycle<std::vec::IntoIter<T>>);

impl<T: Clone> Default for RandomSource<T> {
    fn default() -> Self {
        RandomSource(Vec::new().into_iter().cycle())
    }
}

impl<T: Copy> RandomSource<T> {
    fn next(&mut self) -> T {
        self.0.next().unwrap()
    }
}

impl<T: Clone> RandomSource<T> {
    fn gen_n_with<F: Fn(u64) -> T>(&mut self, n: usize, f: F) {
        let mut rng = rand::thread_rng();
        let mut v = Vec::new();
        for _ in 0..n {
            v.push(f(rng.gen::<u64>()));
        }
        self.0 = v.clone().into_iter().cycle();
    }
}

impl<T: From<u64> + Clone> RandomSource<T> {
    fn gen_n(&mut self, n: usize) {
        let mut rng = rand::thread_rng();
        let mut v = Vec::new();
        for _ in 0..n {
            v.push(rng.gen::<u64>().into());
        }
        self.0 = v.clone().into_iter().cycle();
    }
}

fn gen_hm_80_10_10(n: usize) -> RandomSource<HmOp<u64>> {
    let mut q = std::collections::VecDeque::new();
    let mut rng = rand::thread_rng();
    let mut v = Vec::new();
    for _ in 0..n {
        let op = match HmOp::make_80_10_10(rng.gen()) {
            HmOp::Insert(n) => {
                q.push_back(n);
                HmOp::Insert(n)
            }
            HmOp::Query(n) => HmOp::Query(n),
            HmOp::Delete(n) => HmOp::Delete(q.pop_front().unwrap_or(n)),
        };
        v.push(op);
    }
    RandomSource(v.clone().into_iter().cycle())
}

fn gen_n_perm(n: usize) -> RandomSource<u64> {
    let mut rng = rand::thread_rng();
    let mut v = (0..n as u64).collect::<Vec<_>>();
    rng.shuffle(&mut v);
    RandomSource(v.into_iter().cycle())
}


////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/// Global state for the CMR hashmap.
struct StackState {
    stack: cmr::Box<Stack<u64>>,
}

impl Default for StackState {
    fn default() -> Self {
        StackState { stack: Stack::new_box() }
    }
}

/// Possible operations to perform on a stack.
#[derive(Clone, Copy)]
enum StackOp<T: Clone + Copy> {
    Push(T),
    Pop,
}

impl StackOp<u64> {
    fn rand(n: u64) -> Self {
        let lim = std::u64::MAX / 2;
        if n > lim {
            StackOp::Push(n)
        } else {
            StackOp::Pop
        }
    }
}


fn stack_push(num_threads: usize) {
    type Local = RandomSource<u64>;
    fn func(state: &StackState, local: &mut Local) {
        state.stack.push(local.next());
    }

    let b = trench::TimedBench::<StackState, Local>::with_threads(num_threads);
    b.with_local_state(|l| {
        cmr::thread_activate();
        l.gen_n(10_000_000);
    });
    let res = b.run_for(duration(), func);
    b.with_local_state(|_| cmr::thread_deactivate());

    println!(
        "cmr::Stack\tpush\t{} ops/sec",
        fmt_thousands_sep(res.ops_per_sec)
    );
}

fn stack_pop(num_threads: usize) {
    type Local = ();
    fn func(state: &StackState, _local: &mut Local) {
        state.stack.pop().expect(
            "Stack is empty! Increase size, or decrease duration",
        );
    }

    let b = trench::TimedBench::<StackState, Local>::with_threads(num_threads);
    b.with_local_state(|l| cmr::thread_activate());
    b.with_global_state(move |g| for i in 0..(50_000_000 / num_threads as u64) {
        g.stack.push(i);
    });
    let res = b.run_for(Duration::new(1, 0), func);
    b.with_local_state(|s| { cmr::thread_deactivate(); });

    println!(
        "cmr::Stack\tpop\t{} ops/sec",
        fmt_thousands_sep(res.ops_per_sec)
    );
}

fn stack_5050(num_threads: usize) {
    type Local = RandomSource<StackOp<u64>>;
    fn func(state: &StackState, local: &mut Local) {
        match local.next() {
            StackOp::Push(n) => {
                state.stack.push(n);
            }
            StackOp::Pop => {
                state.stack.pop();
            }
        }
    }

    let b = trench::TimedBench::<StackState, Local>::with_threads(num_threads);
    b.with_local_state(|l| {
        cmr::thread_activate();
        l.gen_n_with(10_000_000, StackOp::rand);
    });
    b.with_global_state(move |g| for i in 0..(1_000_000 / num_threads as u64) {
        g.stack.push(i);
    });
    let res = b.run_for(duration(), func);
    b.with_local_state(|_| cmr::thread_deactivate());

    println!(
        "cmr::Stack\t50-50\t{} ops/sec",
        fmt_thousands_sep(res.ops_per_sec)
    );
}

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/// Global state for the CMR hashmap.
struct QueueState {
    queue: cmr::Box<Queue<u64>>,
}

impl Default for QueueState {
    fn default() -> Self {
        QueueState { queue: Queue::new_box() }
    }
}

/// Possible operations to perform on a queue.
#[derive(Clone, Copy)]
enum QueueOp<T: Clone + Copy> {
    Push(T),
    Pop,
}

impl QueueOp<u64> {
    fn rand(n: u64) -> Self {
        let lim = std::u64::MAX / 2;
        if n > lim {
            QueueOp::Push(n)
        } else {
            QueueOp::Pop
        }
    }
}


fn queue_push(num_threads: usize) {
    type Local = RandomSource<u64>;
    fn func(state: &QueueState, local: &mut Local) {
        state.queue.push(local.next());
    }

    let b = trench::TimedBench::<QueueState, Local>::with_threads(num_threads);
    b.with_local_state(|l| {
        cmr::thread_activate();
        l.gen_n(10_000_000);
    });
    let res = b.run_for(duration(), func);
    b.with_local_state(|_| cmr::thread_deactivate());

    println!(
        "cmr::Queue\tpush\t{} ops/sec",
        fmt_thousands_sep(res.ops_per_sec)
    );
}

fn queue_pop(num_threads: usize) {
    type Local = ();
    fn func(state: &QueueState, _local: &mut Local) {
        state.queue.pop().expect(
            "Queue is empty! Increase size, or decrease duration",
        );
    }

    let b = trench::TimedBench::<QueueState, Local>::with_threads(num_threads);
    b.with_local_state(|l| cmr::thread_activate());
    b.with_global_state(move |g| for i in 0..(50_000_000 / num_threads as u64) {
        g.queue.push(i);
    });
    let res = b.run_for(Duration::new(0, 500_000_000), func);
    b.with_local_state(|s| { cmr::thread_deactivate(); });

    println!(
        "cmr::Queue\tpop\t{} ops/sec",
        fmt_thousands_sep(res.ops_per_sec)
    );
}

fn queue_5050(num_threads: usize) {
    type Local = RandomSource<QueueOp<u64>>;
    fn func(state: &QueueState, local: &mut Local) {
        match local.next() {
            QueueOp::Push(n) => {
                state.queue.push(n);
            }
            QueueOp::Pop => {
                state.queue.pop();
            }
        }
    }

    let b = trench::TimedBench::<QueueState, Local>::with_threads(num_threads);
    b.with_local_state(|l| {
        cmr::thread_activate();
        l.gen_n_with(10_000_000, QueueOp::rand);
    });
    b.with_global_state(move |g| for i in 0..(1_000_000 / num_threads as u64) {
        g.queue.push(i);
    });
    let res = b.run_for(duration(), func);
    b.with_local_state(|_| cmr::thread_deactivate());

    println!(
        "cmr::Queue\t50-50\t{} ops/sec",
        fmt_thousands_sep(res.ops_per_sec)
    );
}


////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


/// Global state for the CMR hashmap.
struct HmState {
    hashmap: HashMap<u64, u64>,
}

impl Default for HmState {
    fn default() -> Self {
        HmState { hashmap: HashMap::new() }
    }
}

/// Possible operations to perform on a hashmap.
#[derive(Clone, Copy)]
enum HmOp<T: Clone + Copy> {
    Insert(T),
    Delete(T),
    Query(T),
}

impl HmOp<u64> {
    /// Given a `u64`, make a HmOp accoring to the 80% query, 10% insert, 10% delete
    /// distribution.
    fn make_80_10_10(n: u64) -> Self {
        let f = n as f64;
        let max = std::u64::MAX as f64;
        let frac = f / max;
        if frac < 0.8 {
            HmOp::Query(n)
        } else if frac < 0.9 {
            HmOp::Insert(n)
        } else {
            HmOp::Delete(n)
        }
    }
}



fn hashmap_insert(num_threads: usize) {
    fn func(state: &HmState, local: &mut RandomSource<u64>) {
        state.hashmap.insert(local.next(), 0);
    }

    let b = trench::TimedBench::<HmState, RandomSource<u64>>::with_threads(num_threads);
    b.with_local_state(|l| {
        cmr::thread_activate();
        l.gen_n(10_000_000);
    });
    let res = b.run_for(duration(), func);
    b.with_local_state(|_| cmr::thread_deactivate());

    println!(
        "cmr::HashMap\tinsert\t{} ops/sec",
        fmt_thousands_sep(res.ops_per_sec)
    );
}

fn hashmap_contains(num_threads: usize) {
    fn func(state: &HmState, local: &mut RandomSource<u64>) {
        let ret = state.hashmap.contains(&local.next());
        trench::black_box(ret);
    }

    let b = trench::TimedBench::<HmState, RandomSource<u64>>::with_threads(num_threads);
    b.with_local_state(|l| {
        cmr::thread_activate();
        l.gen_n(10_000_000);
    });
    b.with_global_state(move |g| {
        let mut rng = rand::thread_rng();
        for i in 0..(1_000_000 / num_threads as u64) {
            g.hashmap.insert(rng.gen(), i);
        }
    });
    let res = b.run_for(duration(), func);
    b.with_local_state(|_| cmr::thread_deactivate());
    println!(
        "cmr::HashMap\tcontains\t{} ops/sec",
        fmt_thousands_sep(res.ops_per_sec)
    );
}

fn hashmap_remove(num_threads: usize) {
    fn func(state: &HmState, local: &mut RandomSource<u64>) {
        let ret = state.hashmap.remove(&local.next());
        trench::black_box(ret);
    }
    let b = trench::TimedBench::<HmState, RandomSource<u64>>::with_threads(num_threads);
    b.with_local_state(|l| {
        cmr::thread_activate();
        *l = gen_n_perm(40_000_000);
    });
    b.with_global_state(move |g| {
        let mut rng = rand::thread_rng();
        for _ in 0..(10_000_000 / num_threads as u64) {
            let n = rng.gen::<u64>() % 40_000_000;
            g.hashmap.insert(n, n);
        }
    });
    let res = b.run_for(duration(), func);
    b.with_local_state(|_| cmr::thread_deactivate());
    println!(
        "cmr::HashMap\tremove\t{} ops/sec",
        fmt_thousands_sep(res.ops_per_sec)
    );
}

fn hashmap_80_10_10(num_threads: usize) {
    fn func(state: &HmState, local: &mut RandomSource<HmOp<u64>>) {
        match local.next() {
            HmOp::Insert(n) => {
                state.hashmap.insert(n, n);
            }
            HmOp::Query(n) => {
                trench::black_box(state.hashmap.contains(&n));
            }
            HmOp::Delete(n) => {
                trench::black_box(state.hashmap.remove(&n));
            }
        }
    }
    let b = trench::TimedBench::<HmState, RandomSource<HmOp<u64>>>::with_threads(num_threads);
    b.with_local_state(|l| {
        cmr::thread_activate();
        *l = gen_hm_80_10_10(10_000_000);
    });
    b.with_global_state(move |s| {
        let mut rng = rand::thread_rng();
        for i in 0..(1_000_000 / num_threads as u64) {
            s.hashmap.insert(rng.gen(), i);
        }
    });
    b.sync();
    let res = b.run_for(duration(), func);
    b.with_local_state(|_| cmr::thread_deactivate());
    println!(
        "cmr::HashMap\t80-10-10\t{} ops/sec",
        fmt_thousands_sep(res.ops_per_sec)
    );
}

fn main() {
    #[cfg(debug_assertions)]
    panic!("You are running a benchmark without optimizations. Please don't.");
    let args = lapp::parse_args(
        "
        Benchmark runner for CMR.
        -t, --threads (integer...)
        <idents> (string...)
    ",
    );

    cmr::global_init();
    cmr::thread_activate();

    let mut all_benches = vec![
        S!(hashmap_insert),
        S!(hashmap_contains),
        S!(hashmap_remove),
        S!(hashmap_80_10_10),

        // S!(queue_push),
        // S!(queue_pop),
        // S!(queue_5050),
 
        // S!(stack_push),
        // S!(stack_pop),
        // S!(stack_5050),
    ];

    let mut threads = args.get_integers("threads");
    if threads.len() == 0 {
        threads = vec![1, 2, 4];
    }

    let idents = args.get_strings("idents");
    if idents.len() > 0 {
        all_benches.retain(|(name, _)| idents.iter().any(|ident| name.contains(ident)));
    }

    for (_name, func) in all_benches.iter() {
        for &num_threads in &threads {
            print!("{}\t", num_threads);
            func(num_threads as usize);
            cmr::do_consolidate();
        }
    }
}