|
| 1 | +use criterion::{criterion_group, criterion_main, Criterion}; |
| 2 | +use futures::channel::oneshot; |
| 3 | +use futures::executor; |
| 4 | +use std::sync::Arc; |
| 5 | +use std::time::Instant; |
| 6 | +use tokio::runtime::Runtime; |
| 7 | +use tokio_postgres::{Client, NoTls}; |
| 8 | + |
| 9 | +fn setup() -> (Client, Runtime) { |
| 10 | + let runtime = Runtime::new().unwrap(); |
| 11 | + let (client, conn) = runtime |
| 12 | + .block_on(tokio_postgres::connect( |
| 13 | + "host=localhost port=5433 user=postgres", |
| 14 | + NoTls, |
| 15 | + )) |
| 16 | + .unwrap(); |
| 17 | + runtime.spawn(async { conn.await.unwrap() }); |
| 18 | + (client, runtime) |
| 19 | +} |
| 20 | + |
| 21 | +fn query_prepared(c: &mut Criterion) { |
| 22 | + let (client, runtime) = setup(); |
| 23 | + let statement = runtime.block_on(client.prepare("SELECT $1::INT8")).unwrap(); |
| 24 | + c.bench_function("runtime_block_on", move |b| { |
| 25 | + b.iter(|| { |
| 26 | + runtime |
| 27 | + .block_on(client.query(&statement, &[&1i64])) |
| 28 | + .unwrap() |
| 29 | + }) |
| 30 | + }); |
| 31 | + |
| 32 | + let (client, runtime) = setup(); |
| 33 | + let statement = runtime.block_on(client.prepare("SELECT $1::INT8")).unwrap(); |
| 34 | + c.bench_function("executor_block_on", move |b| { |
| 35 | + b.iter(|| { |
| 36 | + executor::block_on(client.query(&statement, &[&1i64])).unwrap() |
| 37 | + }) |
| 38 | + }); |
| 39 | + |
| 40 | + let (client, runtime) = setup(); |
| 41 | + let client = Arc::new(client); |
| 42 | + let statement = runtime.block_on(client.prepare("SELECT $1::INT8")).unwrap(); |
| 43 | + c.bench_function("spawned", move |b| { |
| 44 | + b.iter_custom(|iters| { |
| 45 | + let (tx, rx) = oneshot::channel(); |
| 46 | + let client = client.clone(); |
| 47 | + let statement = statement.clone(); |
| 48 | + runtime.spawn(async move { |
| 49 | + let start = Instant::now(); |
| 50 | + for _ in 0..iters { |
| 51 | + client.query(&statement, &[&1i64]).await.unwrap(); |
| 52 | + } |
| 53 | + tx.send(start.elapsed()).unwrap(); |
| 54 | + }); |
| 55 | + executor::block_on(rx).unwrap() |
| 56 | + }) |
| 57 | + }); |
| 58 | +} |
| 59 | + |
| 60 | +criterion_group!(benches, query_prepared); |
| 61 | +criterion_main!(benches); |
0 commit comments