Skip to content

Commit

Permalink
Add example bench
Browse files Browse the repository at this point in the history
  • Loading branch information
Einliterflasche committed Sep 25, 2023
1 parent 02d10fc commit 60db22d
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 2 deletions.
12 changes: 10 additions & 2 deletions pg-worm/benches/bench.rs
Original file line number Diff line number Diff line change
@@ -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)]
Expand Down Expand Up @@ -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);
71 changes: 71 additions & 0 deletions pg-worm/examples/simple_bench.rs
Original file line number Diff line number Diff line change
@@ -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<u128> {
fn avg(&self) -> f64 {
(self.iter().sum::<u128>() as f64) / (self.len() as f64)
}
}

async fn test_n_times_nanos<T>(n: usize, f: impl Fn(i64) -> T) -> Vec<u128>
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<dyn std::error::Error>> {
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(())
}

0 comments on commit 60db22d

Please sign in to comment.