1 | #![cfg (unix)] |
2 | |
3 | use tokio_stream::StreamExt; |
4 | |
5 | use tokio::fs::File; |
6 | use tokio::io::AsyncReadExt; |
7 | use tokio_util::codec::{BytesCodec, FramedRead /*FramedWrite*/}; |
8 | |
9 | use criterion::{criterion_group, criterion_main, Criterion}; |
10 | |
11 | use std::fs::File as StdFile; |
12 | use std::io::Read as StdRead; |
13 | |
14 | fn rt() -> tokio::runtime::Runtime { |
15 | tokio::runtime::Builder::new_multi_thread() |
16 | .worker_threads(2) |
17 | .build() |
18 | .unwrap() |
19 | } |
20 | |
21 | const BLOCK_COUNT: usize = 1_000; |
22 | |
23 | const BUFFER_SIZE: usize = 4096; |
24 | const DEV_ZERO: &str = "/dev/zero" ; |
25 | |
26 | fn async_read_codec(c: &mut Criterion) { |
27 | let rt = rt(); |
28 | |
29 | c.bench_function("async_read_codec" , |b| { |
30 | b.iter(|| { |
31 | let task = || async { |
32 | let file = File::open(DEV_ZERO).await.unwrap(); |
33 | let mut input_stream = |
34 | FramedRead::with_capacity(file, BytesCodec::new(), BUFFER_SIZE); |
35 | |
36 | for _i in 0..BLOCK_COUNT { |
37 | let _bytes = input_stream.next().await.unwrap(); |
38 | } |
39 | }; |
40 | |
41 | rt.block_on(task()); |
42 | }) |
43 | }); |
44 | } |
45 | |
46 | fn async_read_buf(c: &mut Criterion) { |
47 | let rt = rt(); |
48 | |
49 | c.bench_function("async_read_buf" , |b| { |
50 | b.iter(|| { |
51 | let task = || async { |
52 | let mut file = File::open(DEV_ZERO).await.unwrap(); |
53 | let mut buffer = [0u8; BUFFER_SIZE]; |
54 | |
55 | for _i in 0..BLOCK_COUNT { |
56 | let count = file.read(&mut buffer).await.unwrap(); |
57 | if count == 0 { |
58 | break; |
59 | } |
60 | } |
61 | }; |
62 | |
63 | rt.block_on(task()); |
64 | }); |
65 | }); |
66 | } |
67 | |
68 | fn async_read_std_file(c: &mut Criterion) { |
69 | let rt = rt(); |
70 | |
71 | c.bench_function("async_read_std_file" , |b| { |
72 | b.iter(|| { |
73 | let task = || async { |
74 | let mut file = |
75 | tokio::task::block_in_place(|| Box::pin(StdFile::open(DEV_ZERO).unwrap())); |
76 | |
77 | for _i in 0..BLOCK_COUNT { |
78 | let mut buffer = [0u8; BUFFER_SIZE]; |
79 | let mut file_ref = file.as_mut(); |
80 | |
81 | tokio::task::block_in_place(move || { |
82 | file_ref.read_exact(&mut buffer).unwrap(); |
83 | }); |
84 | } |
85 | }; |
86 | |
87 | rt.block_on(task()); |
88 | }); |
89 | }); |
90 | } |
91 | |
92 | fn sync_read(c: &mut Criterion) { |
93 | c.bench_function("sync_read" , |b| { |
94 | b.iter(|| { |
95 | let mut file = StdFile::open(DEV_ZERO).unwrap(); |
96 | let mut buffer = [0u8; BUFFER_SIZE]; |
97 | |
98 | for _i in 0..BLOCK_COUNT { |
99 | file.read_exact(&mut buffer).unwrap(); |
100 | } |
101 | }) |
102 | }); |
103 | } |
104 | |
105 | criterion_group!( |
106 | file, |
107 | async_read_std_file, |
108 | async_read_buf, |
109 | async_read_codec, |
110 | sync_read |
111 | ); |
112 | criterion_main!(file); |
113 | |