Last active
September 30, 2022 02:06
-
-
Save autotaker/ebcf3a5bb1d21fc6c59bf16d3a4446db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: