From 3607eb93b9710a97d0c7911c44d7a2ec7dacd832 Mon Sep 17 00:00:00 2001 From: daixi98 Date: Sun, 12 Jun 2022 22:17:23 -0700 Subject: [PATCH] Add docs and examples for async functions --- book/src/user_guide/benchmarking_async.md | 22 ++++++++++++++++++++++ src/bencher.rs | 22 ++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/book/src/user_guide/benchmarking_async.md b/book/src/user_guide/benchmarking_async.md index 2fda6640..e1c62226 100644 --- a/book/src/user_guide/benchmarking_async.md +++ b/book/src/user_guide/benchmarking_async.md @@ -52,6 +52,28 @@ request. | futures | "async_futures" | `FuturesExecutor` | | Other | "async" | | +### An Example with tokio::runtime::Runtime + +```rust + +// Compile Criterion.rs with features = ["async_tokio"] +#[macro_use] extern crate criterion; + +use criterion::*; + +fn bench(c: &mut Criterion) { + let rt = tokio::runtime::Runtime::new().unwrap(); + c.bench_function("tokio_thread_sleep", move |b| { + b.to_async(&rt).iter(|| async move { + tokio::time::sleep(Duration::from_millis(10)).await; + }) + }); +} + +criterion_group!(benches, bench); +criterion_main!(benches); +``` + ### Considerations when benchmarking async functions Async functions naturally result in more measurement overhead than synchronous functions. It is diff --git a/src/bencher.rs b/src/bencher.rs index c5e90af5..fc66f705 100644 --- a/src/bencher.rs +++ b/src/bencher.rs @@ -388,6 +388,28 @@ impl<'a, M: Measurement> Bencher<'a, M> { } /// Convert this bencher into an AsyncBencher, which enables async/await support. + /// + /// # Example + /// + /// ```rust + /// // Compile Criterion.rs with features = ["async_tokio"] + /// #[macro_use] extern crate criterion; + /// + /// use criterion::*; + /// + /// fn bench(c: &mut Criterion) { + /// let rt = tokio::runtime::Runtime::new().unwrap(); + /// c.bench_function("tokio_thread_sleep", move |b| { + /// b.to_async(&rt).iter(|| async move { + /// tokio::time::sleep(Duration::from_millis(10)).await; + /// }) + /// }); + /// } + /// + /// criterion_group!(benches, bench); + /// criterion_main!(benches); + /// ``` + /// #[cfg(feature = "async")] pub fn to_async<'b, A: AsyncExecutor>(&'b mut self, runner: A) -> AsyncBencher<'a, 'b, A, M> { AsyncBencher { b: self, runner }