1#![cfg(unix)]
2
3use tokio_stream::StreamExt;
4
5use tokio::fs::File;
6use tokio::io::AsyncReadExt;
7use tokio_util::codec::{BytesCodec, FramedRead /*FramedWrite*/};
8
9use criterion::{criterion_group, criterion_main, Criterion};
10
11use std::fs::File as StdFile;
12use std::io::Read as StdRead;
13
14fn rt() -> tokio::runtime::Runtime {
15 tokio::runtime::Builder::new_multi_thread()
16 .worker_threads(2)
17 .build()
18 .unwrap()
19}
20
21const BLOCK_COUNT: usize = 1_000;
22
23const BUFFER_SIZE: usize = 4096;
24const DEV_ZERO: &str = "/dev/zero";
25
26fn 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
46fn 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
68fn 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
92fn 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
105criterion_group!(
106 file,
107 async_read_std_file,
108 async_read_buf,
109 async_read_codec,
110 sync_read
111);
112criterion_main!(file);
113