Skip to content

Commit

Permalink
Merge pull request #761 from uuid-rs/chore/bulk-example
Browse files Browse the repository at this point in the history
Add an example of generating bulk v7 UUIDs
  • Loading branch information
KodrAus authored Jun 24, 2024
2 parents 4a129e7 + 864239b commit c01feb8
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
36 changes: 35 additions & 1 deletion benches/v7.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
))
});
}
4 changes: 4 additions & 0 deletions examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
15 changes: 15 additions & 0 deletions examples/src/sortable_uuid_bulk.rs
Original file line number Diff line number Diff line change
@@ -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)));
}
}

0 comments on commit c01feb8

Please sign in to comment.