File: arccache.rs

package info (click to toggle)
rust-concread 0.4.6-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,076 kB
  • sloc: makefile: 6; sh: 1
file content (631 lines) | stat: -rw-r--r-- 18,841 bytes parent folder | download | duplicates (2)
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
use function_name::named;
use rand::distributions::uniform::SampleUniform;
use rand::{thread_rng, Rng};
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
// use uuid::Uuid;

use concread::arcache::{ARCache, ARCacheBuilder};
use concread::threadcache::ThreadLocal;
use criterion::measurement::{Measurement, ValueFormatter};

pub static RUNNING: AtomicBool = AtomicBool::new(false);

/*
 * A fixed dataset size, with various % of cache pressure (5, 10, 20, 40, 60, 80, 110)
 * ^
 * \--- then vary the dataset sizes. Inclusions are always processed here.
 * -- vary the miss time/penalty as well?
 *
 * -- this measures time to complete.
 *
 * As above but could we measure hit rate as well?
 *
 */
#[derive(Debug)]
struct DataPoint {
    elapsed: Duration,
    #[allow(dead_code)]
    csize: usize,
    hit_count: u32,
    attempt: u32,
    #[allow(dead_code)]
    hit_pct: f64,
}

#[derive(Clone)]
enum AccessPattern<T>
where
    T: SampleUniform + PartialOrd + Clone,
{
    Random(T, T),
}

impl<T> AccessPattern<T>
where
    T: SampleUniform + PartialOrd + Clone,
{
    fn next(&self) -> T {
        match self {
            AccessPattern::Random(min, max) => {
                let mut rng = thread_rng();
                rng.gen_range(min.clone()..max.clone())
            }
        }
    }
}

pub struct HitPercentageFormatter;

impl ValueFormatter for HitPercentageFormatter {
    fn format_value(&self, value: f64) -> String {
        // eprintln!("⚠️  format_value -> {:?}", value);
        format!("{}%", value)
    }

    fn format_throughput(&self, _throughput: &Throughput, value: f64) -> String {
        // eprintln!("⚠️  format_throughput -> {:?}", value);
        format!("{}%", value)
    }

    fn scale_values(&self, _typical_value: f64, _values: &mut [f64]) -> &'static str {
        // eprintln!("⚠️  scale_values -> typ {:?} : {:?}", typical_value, values);
        // panic!();
        "%"
    }

    fn scale_throughputs(
        &self,
        _typical_value: f64,
        _throughput: &Throughput,
        _values: &mut [f64],
    ) -> &'static str {
        // eprintln!("⚠️  scale_throughputs -> {:?}", values);
        "%"
    }

    fn scale_for_machines(&self, _values: &mut [f64]) -> &'static str {
        // eprintln!("⚠️  scale_machines -> {:?}", values);
        "%"
    }
}

pub struct HitPercentage;

impl Measurement for HitPercentage {
    type Intermediate = (u32, u32);
    type Value = (u32, u32);

    fn start(&self) -> Self::Intermediate {
        unreachable!("HitPercentage requires the use of iter_custom");
    }

    fn end(&self, i: Self::Intermediate) -> Self::Value {
        // eprintln!("⚠️  end -> {:?}", i);
        i
    }

    fn add(&self, v1: &Self::Value, v2: &Self::Value) -> Self::Value {
        // eprintln!("⚠️  add -> {:?} + {:?}", v1, v2);
        (v1.0 + v2.0, v1.1 + v2.1)
    }

    fn zero(&self) -> Self::Value {
        // eprintln!("⚠️  zero -> (0,0)");
        (0, 0)
    }

    fn to_f64(&self, val: &Self::Value) -> f64 {
        let x = (f64::from(val.0) / f64::from(val.1)) * 100.0;
        // eprintln!("⚠️  to_f64 -> {:?} -> {:?}", val, x);
        x
    }

    fn formatter(&self) -> &dyn ValueFormatter {
        &HitPercentageFormatter
    }
}

fn tlocal_multi_thread_worker<K, V>(
    mut cache: ThreadLocal<K, V>,
    backing_set: Arc<HashMap<K, V>>,
    backing_set_delay: Option<Duration>,
    access_pattern: AccessPattern<K>,
) where
    K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static + SampleUniform + PartialOrd,
    V: Clone + Debug + Sync + Send + 'static,
{
    while RUNNING.load(Ordering::Relaxed) {
        let k = access_pattern.next();
        let v = backing_set.get(&k).cloned().unwrap();

        let mut rd_txn = cache.read();
        // hit/miss process.
        if !rd_txn.contains_key(&k) {
            if let Some(delay) = backing_set_delay {
                thread::sleep(delay);
            }
            rd_txn.insert(k, v);
        }
    }
}

fn run_tlocal_multi_thread_test<K, V>(
    // Number of iterations
    iters: u64,
    // Number of iters to warm the cache.
    warm_iters: u64,
    // pct of backing set size to configure into the cache.
    cache_size_pct: u64,
    // backing set.
    backing_set: HashMap<K, V>,
    // backing set access delay on miss
    backing_set_delay: Option<Duration>,
    // How to lookup keys during each iter.
    access_pattern: AccessPattern<K>,
    // How many threads?
    thread_count: usize,
) -> DataPoint
where
    K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static + SampleUniform + PartialOrd,
    V: Clone + Debug + Sync + Send + 'static,
{
    assert!(thread_count > 1);

    let mut csize = ((backing_set.len() / 100) * (cache_size_pct as usize)) / thread_count;
    if csize == 0 {
        csize = 1;
    }

    let mut tlocals = ThreadLocal::new(4, csize);
    let mut cache = tlocals.pop().expect("Can't get local cache.");

    let backing_set = Arc::new(backing_set);

    // Setup our sync
    RUNNING.store(true, Ordering::Relaxed);

    // Warm up
    let mut wr_txn = cache.write();
    for _i in 0..warm_iters {
        let k = access_pattern.next();
        let v = backing_set.get(&k).cloned().unwrap();

        // hit/miss process.
        if !wr_txn.contains_key(&k) {
            wr_txn.insert(k, v);
        }
    }
    wr_txn.commit();

    // Start some bg threads.
    let handles: Vec<_> = tlocals
        .into_iter()
        .map(|cache| {
            // Build the threads.
            let back_set = backing_set.clone();
            let back_set_delay = backing_set_delay.clone();
            let pat = access_pattern.clone();
            thread::spawn(move || tlocal_multi_thread_worker(cache, back_set, back_set_delay, pat))
        })
        .collect();

    // We do our measurement in this thread.
    let mut elapsed = Duration::from_secs(0);
    let mut hit_count = 0;
    let mut attempt = 0;

    for _i in 0..iters {
        attempt += 1;
        let k = access_pattern.next();
        let v = backing_set.get(&k).cloned().unwrap();

        let start = Instant::now();
        let mut wr_txn = cache.write();
        // hit/miss process.
        if wr_txn.contains_key(&k) {
            hit_count += 1;
        } else {
            if let Some(delay) = backing_set_delay {
                thread::sleep(delay);
            }
            wr_txn.insert(k, v);
        }
        wr_txn.commit();
        elapsed = elapsed.checked_add(start.elapsed()).unwrap();
    }

    // Stop our bg threads (how to signal?)
    RUNNING.store(false, Ordering::Relaxed);

    // Join them.
    handles
        .into_iter()
        .for_each(|th| th.join().expect("Can't join thread"));

    // Return our data.
    let hit_pct = (f64::from(hit_count as u32) / f64::from(iters as u32)) * 100.0;
    DataPoint {
        elapsed,
        csize,
        hit_count,
        attempt,
        hit_pct,
    }
}

fn multi_thread_worker<K, V>(
    arc: Arc<ARCache<K, V>>,
    backing_set: Arc<HashMap<K, V>>,
    backing_set_delay: Option<Duration>,
    access_pattern: AccessPattern<K>,
) where
    K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static + SampleUniform + PartialOrd,
    V: Clone + Debug + Sync + Send + 'static,
{
    while RUNNING.load(Ordering::Relaxed) {
        let k = access_pattern.next();
        let v = backing_set.get(&k).cloned().unwrap();

        let mut rd_txn = arc.read();
        // hit/miss process.
        if !rd_txn.contains_key(&k) {
            if let Some(delay) = backing_set_delay {
                thread::sleep(delay);
            }
            rd_txn.insert(k, v);
        }
    }
}

fn run_multi_thread_test<K, V>(
    // Number of iterations
    iters: u64,
    // Number of iters to warm the cache.
    warm_iters: u64,
    // pct of backing set size to configure into the cache.
    cache_size_pct: u64,
    // backing set.
    backing_set: HashMap<K, V>,
    // backing set access delay on miss
    backing_set_delay: Option<Duration>,
    // How to lookup keys during each iter.
    access_pattern: AccessPattern<K>,
    // How many threads?
    thread_count: usize,
) -> DataPoint
where
    K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static + SampleUniform + PartialOrd,
    V: Clone + Debug + Sync + Send + 'static,
{
    assert!(thread_count > 1);

    let mut csize = (backing_set.len() / 100) * (cache_size_pct as usize);
    if csize == 0 {
        csize = 1;
    }

    let arc: Arc<ARCache<K, V>> = Arc::new(
        ARCacheBuilder::new()
            .set_size(csize, 0)
            .set_watermark(0)
            .set_reader_quiesce(false)
            .build()
            .unwrap(),
    );

    let backing_set = Arc::new(backing_set);

    // Setup our sync
    RUNNING.store(true, Ordering::Relaxed);

    // Warm up
    let mut wr_txn = arc.write();
    for _i in 0..warm_iters {
        let k = access_pattern.next();
        let v = backing_set.get(&k).cloned().unwrap();

        // hit/miss process.
        let cont = wr_txn.contains_key(&k);
        if !cont {
            wr_txn.insert(k, v);
        }
    }
    wr_txn.commit();

    // Start some bg threads.
    let handles: Vec<_> = (0..(thread_count - 1))
        .into_iter()
        .map(|_| {
            // Build the threads.
            let cache = arc.clone();
            let back_set = backing_set.clone();
            let back_set_delay = backing_set_delay.clone();
            let pat = access_pattern.clone();
            thread::spawn(move || multi_thread_worker(cache, back_set, back_set_delay, pat))
        })
        .collect();

    // We do our measurement in this thread.
    let mut elapsed = Duration::from_secs(0);
    let mut hit_count = 0;
    let mut attempt = 0;

    for _i in 0..iters {
        attempt += 1;
        let k = access_pattern.next();
        let v = backing_set.get(&k).cloned().unwrap();

        let start = Instant::now();
        let mut wr_txn = arc.write();
        // eprintln!("lock took - {:?}", start.elapsed());
        // hit/miss process.
        if wr_txn.contains_key(&k) {
            hit_count += 1;
        } else {
            if let Some(delay) = backing_set_delay {
                thread::sleep(delay);
            }
            wr_txn.insert(k, v);
        }
        wr_txn.commit();
        elapsed = elapsed.checked_add(start.elapsed()).unwrap();
    }

    // Stop our bg threads (how to signal?)
    RUNNING.store(false, Ordering::Relaxed);

    // Join them.
    handles
        .into_iter()
        .for_each(|th| th.join().expect("Can't join thread"));

    // Return our data.
    let hit_pct = (f64::from(hit_count as u32) / f64::from(iters as u32)) * 100.0;
    DataPoint {
        elapsed,
        csize,
        hit_count,
        attempt,
        hit_pct,
    }
}

fn run_single_thread_test<K, V>(
    // Number of iterations
    iters: u64,
    // Number of iters to warm the cache.
    warm_iters: u64,
    // pct of backing set size to configure into the cache.
    cache_size_pct: u64,
    // backing set.
    backing_set: HashMap<K, V>,
    // backing set access delay on miss
    backing_set_delay: Option<Duration>,
    // How to lookup keys during each iter.
    access_pattern: AccessPattern<K>,
) -> DataPoint
where
    K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static + SampleUniform + PartialOrd,
    V: Clone + Debug + Sync + Send + 'static,
{
    let mut csize = (backing_set.len() / 100) * (cache_size_pct as usize);
    if csize == 0 {
        csize = 1;
    }

    let arc: ARCache<K, V> = ARCacheBuilder::new()
        .set_size(csize, 0)
        .set_watermark(0)
        .set_reader_quiesce(false)
        .build()
        .unwrap();

    let mut elapsed = Duration::from_secs(0);
    let mut hit_count = 0;
    let mut attempt = 0;

    let mut wr_txn = arc.write();
    for _i in 0..warm_iters {
        let k = access_pattern.next();
        let v = backing_set.get(&k).cloned().unwrap();

        // hit/miss process.
        if !wr_txn.contains_key(&k) {
            wr_txn.insert(k, v);
        }
    }
    wr_txn.commit();

    for _i in 0..iters {
        attempt += 1;
        let k = access_pattern.next();
        let v = backing_set.get(&k).cloned().unwrap();

        let start = Instant::now();
        let mut wr_txn = arc.write();
        // hit/miss process.
        let cont = wr_txn.contains_key(&k);
        if cont {
            hit_count += 1;
        } else {
            if let Some(delay) = backing_set_delay {
                thread::sleep(delay);
            }
            wr_txn.insert(k, v);
        }
        wr_txn.commit();
        elapsed = elapsed.checked_add(start.elapsed()).unwrap();
    }

    let hit_pct = (f64::from(hit_count as u32) / f64::from(iters as u32)) * 100.0;
    DataPoint {
        elapsed,
        csize,
        hit_count,
        attempt,
        hit_pct,
    }
}

macro_rules! tlocal_multi_thread_x_small_latency {
    ($c:expr, $max:expr, $measure:expr) => {
        let mut group = $c.benchmark_group(function_name!());
        group.warm_up_time(Duration::from_secs(10));
        group.measurement_time(Duration::from_secs(60));
        for pct in &[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110] {
            group.bench_with_input(BenchmarkId::from_parameter(pct), &$max, |b, &max| {
                b.iter_custom(|iters| {
                    let mut backing_set: HashMap<usize, usize> = HashMap::with_capacity(max);
                    (0..$max).for_each(|i| {
                        backing_set.insert(i, i);
                    });
                    let data = run_tlocal_multi_thread_test(
                        iters,
                        iters / 5,
                        *pct,
                        backing_set,
                        Some(Duration::from_nanos(5)),
                        AccessPattern::Random(0, max),
                        4,
                    );
                    println!("{:?}", data);
                    data.elapsed
                })
            });
        }
        group.finish();
    };
}

macro_rules! basic_multi_thread_x_small_latency {
    ($c:expr, $max:expr, $measure:expr) => {
        let mut group = $c.benchmark_group(function_name!());
        group.warm_up_time(Duration::from_secs(10));
        group.measurement_time(Duration::from_secs(60));
        for pct in &[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110] {
            group.bench_with_input(BenchmarkId::from_parameter(pct), &$max, |b, &max| {
                b.iter_custom(|iters| {
                    let mut backing_set: HashMap<usize, usize> = HashMap::with_capacity(max);
                    (0..$max).for_each(|i| {
                        backing_set.insert(i, i);
                    });
                    let data = run_multi_thread_test(
                        iters,
                        iters / 5,
                        *pct,
                        backing_set,
                        Some(Duration::from_nanos(5)),
                        AccessPattern::Random(0, max),
                        4,
                    );
                    println!("{:?}", data);
                    data.elapsed
                })
            });
        }
        group.finish();
    };
}

macro_rules! basic_single_thread_x_small_latency {
    ($c:expr, $max:expr, $measure:expr) => {
        let mut group = $c.benchmark_group(function_name!());
        group.warm_up_time(Duration::from_secs(10));
        for pct in &[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110] {
            group.bench_with_input(BenchmarkId::from_parameter(pct), &$max, |b, &max| {
                b.iter_custom(|iters| {
                    let mut backing_set: HashMap<usize, usize> = HashMap::with_capacity(max);
                    (0..$max).for_each(|i| {
                        backing_set.insert(i, i);
                    });
                    let data = run_single_thread_test(
                        iters,
                        iters / 5,
                        *pct,
                        backing_set,
                        Some(Duration::from_nanos(5)),
                        AccessPattern::Random(0, max),
                    );
                    println!("{:?}", data);
                    data.elapsed
                })
            });
        }
        group.finish();
    };
}

macro_rules! basic_single_thread_x_small_pct {
    ($c:expr, $max:expr, $measure:expr) => {
        let mut group = $c.benchmark_group(function_name!());
        group.warm_up_time(Duration::from_secs(10));
        for pct in &[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110] {
            group.bench_with_input(BenchmarkId::from_parameter(pct), &$max, |b, &max| {
                b.iter_custom(|iters| {
                    let mut backing_set: HashMap<usize, usize> = HashMap::with_capacity(max);
                    (0..$max).for_each(|i| {
                        backing_set.insert(i, i);
                    });
                    let data = run_single_thread_test(
                        iters,
                        iters / 10,
                        *pct,
                        backing_set,
                        Some(Duration::from_nanos(5)),
                        AccessPattern::Random(0, max),
                    );
                    println!("{:?}", data);
                    (data.hit_count, data.attempt)
                })
            });
        }
        group.finish();
    };
}

#[named]
pub fn tlocal_multi_thread_2048_small_latency(c: &mut Criterion) {
    tlocal_multi_thread_x_small_latency!(c, 2048, MeasureType::Latency);
}

#[named]
pub fn basic_multi_thread_2048_small_latency(c: &mut Criterion) {
    basic_multi_thread_x_small_latency!(c, 2048, MeasureType::Latency);
}

#[named]
pub fn basic_single_thread_2048_small_latency(c: &mut Criterion) {
    basic_single_thread_x_small_latency!(c, 2048, MeasureType::Latency);
}

#[named]
pub fn basic_single_thread_2048_small_pct(c: &mut Criterion<HitPercentage>) {
    basic_single_thread_x_small_pct!(c, 2048, MeasureType::HitPct);
}

criterion_group!(
    name = latency;
    config = Criterion::default()
        // .measurement_time(Duration::from_secs(15))
        .with_plots();
    targets = basic_single_thread_2048_small_latency,
              basic_multi_thread_2048_small_latency,
              tlocal_multi_thread_2048_small_latency,


);

criterion_group!(
    name = hit_percent;
    config = Criterion::default().with_measurement(HitPercentage);
    targets = basic_single_thread_2048_small_pct
);

criterion_main!(latency, hit_percent);