sleepy/
sleepy.rs

1// Copyright 2020 Martin Pool
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! Simple demonstration of threaded readahead: generate integers slowly in
10//! an iterator, and consume them also with some delay from the main thread.
11//!
12//! As expected, doing all the work on the main thread takes about
13//! `N * (PROCESS_DELAY + GENERATE_DELAY)`, whereas running them in
14//! parallel improves this to `N * max(PROCESS_DELAY, GENERATE_DELAY)`.
15
16use std::thread::sleep;
17use std::time::{Duration, Instant};
18
19use readahead_iterator::Readahead;
20
21const PROCESS_DELAY: Duration = Duration::from_millis(200);
22const GENERATE_DELAY: Duration = Duration::from_millis(500);
23const N: usize = 20;
24
25fn slow_iterator() -> impl Iterator<Item = usize> {
26    (0..N).inspect(|i| {
27        println!("generating {}...", i);
28        sleep(GENERATE_DELAY);
29    })
30}
31
32pub fn main() {
33    let start = Instant::now();
34    println!("without readahead:");
35    for i in slow_iterator() {
36        println!("processing {}...", i);
37        sleep(PROCESS_DELAY);
38    }
39    println!("elapsed: {:?}", Instant::now() - start);
40
41    let start = Instant::now();
42    println!("with readahead:");
43    for i in Readahead::new(slow_iterator(), 10) {
44        println!("processing {}...", i);
45        sleep(PROCESS_DELAY);
46    }
47    println!("elapsed: {:?}", Instant::now() - start);
48}