summaryrefslogtreecommitdiffstats
path: root/third_party/rust/futures-executor/benches/thread_notify.rs
blob: 88d0447cf68bf7765e6e6ce128893097598e9965 (plain)
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
#![feature(test)]

extern crate test;
use crate::test::Bencher;

use futures::executor::block_on;
use futures::future::Future;
use futures::task::{Context, Poll, Waker};
use std::pin::Pin;

#[bench]
fn thread_yield_single_thread_one_wait(b: &mut Bencher) {
    const NUM: usize = 10_000;

    struct Yield {
        rem: usize,
    }

    impl Future for Yield {
        type Output = ();

        fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
            if self.rem == 0 {
                Poll::Ready(())
            } else {
                self.rem -= 1;
                cx.waker().wake_by_ref();
                Poll::Pending
            }
        }
    }

    b.iter(|| {
        let y = Yield { rem: NUM };
        block_on(y);
    });
}

#[bench]
fn thread_yield_single_thread_many_wait(b: &mut Bencher) {
    const NUM: usize = 10_000;

    struct Yield {
        rem: usize,
    }

    impl Future for Yield {
        type Output = ();

        fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
            if self.rem == 0 {
                Poll::Ready(())
            } else {
                self.rem -= 1;
                cx.waker().wake_by_ref();
                Poll::Pending
            }
        }
    }

    b.iter(|| {
        for _ in 0..NUM {
            let y = Yield { rem: 1 };
            block_on(y);
        }
    });
}

#[bench]
fn thread_yield_multi_thread(b: &mut Bencher) {
    use std::sync::mpsc;
    use std::thread;

    const NUM: usize = 1_000;

    let (tx, rx) = mpsc::sync_channel::<Waker>(10_000);

    struct Yield {
        rem: usize,
        tx: mpsc::SyncSender<Waker>,
    }
    impl Unpin for Yield {}

    impl Future for Yield {
        type Output = ();

        fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
            if self.rem == 0 {
                Poll::Ready(())
            } else {
                self.rem -= 1;
                self.tx.send(cx.waker().clone()).unwrap();
                Poll::Pending
            }
        }
    }

    thread::spawn(move || {
        while let Ok(task) = rx.recv() {
            task.wake();
        }
    });

    b.iter(move || {
        let y = Yield { rem: NUM, tx: tx.clone() };

        block_on(y);
    });
}