Last active
April 10, 2023 12:53
-
-
Save fnordpig/4a5268d937413e2435e99fd904815621 to your computer and use it in GitHub Desktop.
Split benchmark
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 criterion::{black_box, criterion_group, criterion_main, Criterion}; | |
use regex::Regex; | |
use rand::{Rng, distributions::{Alphanumeric, Uniform}}; | |
pub fn criterion_benchmark(c: &mut Criterion) { | |
let reg = Regex::new(®ex::escape("\\")).unwrap(); | |
let mut group = c.benchmark_group("single character"); | |
let mut rng = rand::thread_rng(); | |
let base: usize = 2; | |
for size in (0..30).step_by(10).map(|x| base.pow(x)) { | |
let mut str = (&mut rng).sample_iter(&Alphanumeric).take(size).map(char::from).collect::<String>(); | |
if size > 1 { | |
let replaces = randomly_replace_chars(&str, '\\', size/100); | |
} | |
group.bench_function(format!{"single char escaped {size}"}, |b| b.iter(|| str.split('\\').collect::<Vec<_>>())); | |
group.bench_function(format!("single char escaped regex {size}"), |b| b.iter(|| reg.split(&str).collect::<Vec<_>>())); | |
} | |
group.finish(); | |
} | |
fn randomly_replace_chars(input: &str, replacement: char, num_replacements: usize) -> String { | |
let mut rng = rand::thread_rng(); | |
let mut chars: Vec<char> = input.chars().collect(); | |
let index_dist = Uniform::from(0..chars.len()); | |
for _ in 0..num_replacements { | |
let index = rng.sample(index_dist); | |
chars[index] = replacement; | |
} | |
chars.into_iter().collect() | |
} | |
criterion_group!(benches, criterion_benchmark); | |
criterion_main!{benches} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment