From 864239ba3005be222d9a6c7356d19c1622abd9fb Mon Sep 17 00:00:00 2001 From: Ashley Mannix Date: Mon, 24 Jun 2024 18:59:02 +1000 Subject: [PATCH] add an example of generating bulk v7 UUIDs --- benches/v7.rs | 36 +++++++++++++++++++++++++++++- examples/Cargo.toml | 4 ++++ examples/src/sortable_uuid_bulk.rs | 15 +++++++++++++ 3 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 examples/src/sortable_uuid_bulk.rs diff --git a/benches/v7.rs b/benches/v7.rs index ee279b27..789153b1 100644 --- a/benches/v7.rs +++ b/benches/v7.rs @@ -2,10 +2,44 @@ #![feature(test)] extern crate test; +use std::time::SystemTime; + use test::Bencher; -use uuid::Uuid; +use uuid::{ContextV7, NoContext, Timestamp, Uuid}; #[bench] fn now_v7(b: &mut Bencher) { b.iter(|| Uuid::now_v7()); } + +#[bench] +fn new_v7_no_context(b: &mut Bencher) { + b.iter(|| Uuid::new_v7(Timestamp::now(NoContext))); +} + +#[bench] +fn new_v7_context(b: &mut Bencher) { + let ctxt = ContextV7::new(); + + b.iter(|| Uuid::new_v7(Timestamp::now(&ctxt))); +} + +#[bench] +fn v7_raw(b: &mut Bencher) { + let now = SystemTime::UNIX_EPOCH.elapsed().unwrap(); + let secs = now.as_secs(); + let subsec_nanos = now.subsec_nanos(); + let mut counter = 0; + + b.iter(|| { + Uuid::new_v7(Timestamp::from_unix_time( + secs, + subsec_nanos, + { + counter += 1; + counter + }, + 42, + )) + }); +} diff --git a/examples/Cargo.toml b/examples/Cargo.toml index 1da77e78..56f0560d 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -12,6 +12,10 @@ path = "src/random_uuid.rs" name = "sortable_uuid" path = "src/sortable_uuid.rs" +[[example]] +name = "sortable_uuid_bulk" +path = "src/sortable_uuid_bulk.rs" + [[example]] name = "uuid_macro" path = "src/uuid_macro.rs" diff --git a/examples/src/sortable_uuid_bulk.rs b/examples/src/sortable_uuid_bulk.rs new file mode 100644 index 00000000..16d14cc3 --- /dev/null +++ b/examples/src/sortable_uuid_bulk.rs @@ -0,0 +1,15 @@ +//! Generating a sortable UUID. +//! +//! If you enable the `v7` feature you can generate sortable UUIDs. +//! This example avoids the synchronization cost of `Uuid::now_v7()` +//! when generating UUIDs in bulk. + +fn main() { + use uuid::{ContextV7, Timestamp, Uuid}; + + let ctxt = ContextV7::new(); + + for _ in 0..10 { + println!("{}", Uuid::new_v7(Timestamp::now(&ctxt))); + } +}