Skip to content

Instantly share code, notes, and snippets.

@autotaker
Last active September 30, 2022 02:06
Show Gist options
  • Save autotaker/ebcf3a5bb1d21fc6c59bf16d3a4446db to your computer and use it in GitHub Desktop.
Save autotaker/ebcf3a5bb1d21fc6c59bf16d3a4446db to your computer and use it in GitHub Desktop.
use async_once_cell::OnceCell;
use criterion::{criterion_group, criterion_main, Criterion};
use chrono::{DateTime, Utc};
use sqlx::Executor;
use sqlx::{Connection, PgConnection, PgPool};
use sqlx::{Postgres, Row};
use tokio::runtime::Builder;
pub async fn select_now<'c, E>(executor: E) -> DateTime<Utc>
where
E: Executor<'c, Database = Postgres>,
{
let row = sqlx::query("SELECT NOW()")
.fetch_one(executor)
.await
.unwrap();
let now: DateTime<Utc> = row.try_get("now").unwrap();
now
}
fn bench(c: &mut Criterion) {
c.bench_function("Select Now with an independent runtime", |b| {
b.iter(|| {
let runtime = Builder::new_current_thread().enable_all().build().unwrap();
runtime.block_on(async {
let db_url = std::env::var("DATABASE_URL").expect("No DATABASE_URL is specified");
let mut conn = PgConnection::connect(&db_url).await.unwrap();
select_now(&mut conn).await;
});
});
});
c.bench_function("Select Now with a shared runtime", |b| {
let runtime = Builder::new_current_thread().enable_all().build().unwrap();
let pool = OnceCell::new();
b.iter(|| {
runtime.block_on(async {
let conn = pool
.get_or_init(async {
let db_url =
std::env::var("DATABASE_URL").expect("No DATABASE_URL is specified");
PgPool::connect(&db_url).await.unwrap()
})
.await;
select_now(conn).await;
});
});
});
}
criterion_group!(benches, bench);
criterion_main!(benches);
[package]
name = "async-share"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tokio = { version = "1.21.1", features = ["fs","sync","macros","rt"] }
sqlx = { version = "0.6.2", features = ["postgres","runtime-tokio-rustls","chrono"] }
async-once-cell = "0.4.2"
chrono = "0.4.0"
[dev-dependencies]
criterion = "0.4.0"
[[bench]]
name = "benchmark"
harness = false
@autotaker
Copy link
Author

autotaker commented Sep 30, 2022

Result:

     Running benches/benchmark.rs (/tmp/target/release/deps/benchmark-62dd168396478ae1)
Select Now with an independent runtime
                        time:   [6.9064 ms 6.9880 ms 7.0753 ms]
                        change: [-4.6350% -2.9059% -1.1734%] (p = 0.00 < 0.05)
                        Performance has improved.
Found 3 outliers among 100 measurements (3.00%)
  3 (3.00%) high mild

Select Now with a shared runtime
                        time:   [236.29 µs 241.22 µs 247.55 µs]
                        change: [-39.479% -20.590% +4.8383%] (p = 0.13 > 0.05)
                        No change in performance detected.
Found 12 outliers among 100 measurements (12.00%)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment