From 60db22d16e9990c58bca2c4b9581e91fae8e4d8f Mon Sep 17 00:00:00 2001 From: Einliterflasche Date: Tue, 26 Sep 2023 00:03:45 +0200 Subject: [PATCH] Add example bench --- pg-worm/benches/bench.rs | 12 +++++- pg-worm/examples/simple_bench.rs | 71 ++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 2 deletions(-) create mode 100644 pg-worm/examples/simple_bench.rs diff --git a/pg-worm/benches/bench.rs b/pg-worm/benches/bench.rs index c2e444f..a559218 100644 --- a/pg-worm/benches/bench.rs +++ b/pg-worm/benches/bench.rs @@ -1,7 +1,9 @@ +use std::time::Duration; + use criterion::{criterion_group, criterion_main, Criterion}; use tokio::runtime::Runtime; -use pg_worm::{prelude::*, query::Prepared}; +use pg_worm::prelude::*; #[allow(dead_code)] #[derive(Model)] @@ -45,5 +47,11 @@ fn bench_main(criterion: &mut Criterion) { }); } -criterion_group!(benches, bench_main); +criterion_group!{ + name = benches; + config = Criterion::default() + .sample_size(10) + .measurement_time(Duration::from_millis(100_000)); + targets = bench_main +} criterion_main!(benches); diff --git a/pg-worm/examples/simple_bench.rs b/pg-worm/examples/simple_bench.rs new file mode 100644 index 0000000..631e3a1 --- /dev/null +++ b/pg-worm/examples/simple_bench.rs @@ -0,0 +1,71 @@ +use futures_util::Future; +use pg_worm::{prelude::*, query::Prepared}; +use tokio::time::Instant; + +#[allow(dead_code)] +#[derive(Model, Debug)] +struct Book { + #[column(primary_key, auto)] + id: i64, + title: String +} + +pub trait Average { + fn avg(&self) -> f64; +} + +impl Average for Vec { + fn avg(&self) -> f64 { + (self.iter().sum::() as f64) / (self.len() as f64) + } +} + +async fn test_n_times_nanos(n: usize, f: impl Fn(i64) -> T) -> Vec +where + T: Future +{ + let mut v = Vec::with_capacity(n); + + for i in 0..n { + let f = f(i.try_into().unwrap()); + let before = Instant::now(); + f.await; + let after = Instant::now(); + + v.push(after.duration_since(before).as_nanos()) + } + + v +} + +#[tokio::main] +async fn main() -> Result<(), Box> { + Connection::build("postgres://postgres:postgres@localhost:5432") + .connect() + .await?; + + force_create_table!(Book).await?; + + Book::insert("Foo - Part I").await?; + Book::insert("Foo - Part II").await?; + Book::insert("Foo - Part III").await?; + + const N: usize = 1_000; + let normal = test_n_times_nanos(N, |n| async move { + Book::update() + .set(Book::title, &format!("Foo {n}")) + .where_(Book::id.lt(&n)) + .await.expect("err in book select"); + }).await; + let prepared = test_n_times_nanos(N, |n| async move { + Book::update() + .set(Book::title, &format!("Foo {n}")) + .where_(Book::id.lt(&n)) + .prepared() + .await.expect("err in book select"); + }).await; + + println!("normal avg: {}µs\nprepared avg: {}µs", normal.avg() / 1000f64, prepared.avg() / 1000f64); + + Ok(()) +} \ No newline at end of file