|
| 1 | +#![feature(test)] |
| 2 | +#![deny(warnings)] |
| 3 | + |
| 4 | +extern crate test; |
| 5 | + |
| 6 | +use bytes::Buf; |
| 7 | +use futures_util::stream; |
| 8 | +use futures_util::StreamExt; |
| 9 | +use hyper::body::Body; |
| 10 | + |
| 11 | +macro_rules! bench_stream { |
| 12 | + ($bencher:ident, bytes: $bytes:expr, count: $count:expr, $total_ident:ident, $body_pat:pat, $block:expr) => {{ |
| 13 | + let mut rt = tokio::runtime::Builder::new() |
| 14 | + .basic_scheduler() |
| 15 | + .build() |
| 16 | + .expect("rt build"); |
| 17 | + |
| 18 | + let $total_ident: usize = $bytes * $count; |
| 19 | + $bencher.bytes = $total_ident as u64; |
| 20 | + let __s: &'static [&'static [u8]] = &[&[b'x'; $bytes] as &[u8]; $count] as _; |
| 21 | + |
| 22 | + $bencher.iter(|| { |
| 23 | + rt.block_on(async { |
| 24 | + let $body_pat = Body::wrap_stream( |
| 25 | + stream::iter(__s.iter()).map(|&s| Ok::<_, std::convert::Infallible>(s)), |
| 26 | + ); |
| 27 | + $block; |
| 28 | + }); |
| 29 | + }); |
| 30 | + }}; |
| 31 | +} |
| 32 | + |
| 33 | +macro_rules! benches { |
| 34 | + ($($name:ident, $bytes:expr, $count:expr;)+) => ( |
| 35 | + mod aggregate { |
| 36 | + use super::*; |
| 37 | + |
| 38 | + $( |
| 39 | + #[bench] |
| 40 | + fn $name(b: &mut test::Bencher) { |
| 41 | + bench_stream!(b, bytes: $bytes, count: $count, total, body, { |
| 42 | + let buf = hyper::body::aggregate(body).await.unwrap(); |
| 43 | + assert_eq!(buf.remaining(), total); |
| 44 | + }); |
| 45 | + } |
| 46 | + )+ |
| 47 | + } |
| 48 | + |
| 49 | + mod manual_into_vec { |
| 50 | + use super::*; |
| 51 | + |
| 52 | + $( |
| 53 | + #[bench] |
| 54 | + fn $name(b: &mut test::Bencher) { |
| 55 | + bench_stream!(b, bytes: $bytes, count: $count, total, mut body, { |
| 56 | + let mut vec = Vec::new(); |
| 57 | + while let Some(chunk) = body.next().await { |
| 58 | + vec.extend_from_slice(&chunk.unwrap()); |
| 59 | + } |
| 60 | + assert_eq!(vec.len(), total); |
| 61 | + }); |
| 62 | + } |
| 63 | + )+ |
| 64 | + } |
| 65 | + |
| 66 | + mod to_bytes { |
| 67 | + use super::*; |
| 68 | + |
| 69 | + $( |
| 70 | + #[bench] |
| 71 | + fn $name(b: &mut test::Bencher) { |
| 72 | + bench_stream!(b, bytes: $bytes, count: $count, total, body, { |
| 73 | + let bytes = hyper::body::to_bytes(body).await.unwrap(); |
| 74 | + assert_eq!(bytes.len(), total); |
| 75 | + }); |
| 76 | + } |
| 77 | + )+ |
| 78 | + } |
| 79 | + ) |
| 80 | +} |
| 81 | + |
| 82 | +// ===== Actual Benchmarks ===== |
| 83 | + |
| 84 | +benches! { |
| 85 | + bytes_1_000_count_2, 1_000, 2; |
| 86 | + bytes_1_000_count_10, 1_000, 10; |
| 87 | + bytes_10_000_count_1, 10_000, 1; |
| 88 | + bytes_10_000_count_10, 10_000, 10; |
| 89 | +} |
0 commit comments