From 0a4a5aa6a36bc270fad1154029a751991f310a01 Mon Sep 17 00:00:00 2001 From: Brady Fomegne Date: Sat, 2 Mar 2024 10:19:19 +0100 Subject: [PATCH] test(translator): add bunch test for ::translate (#173) The bunch test will be useful while optimizing of the Translator::translate method. --- engine/translator/Cargo.toml | 7 +++ engine/translator/benches/bench.rs | 71 ++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 engine/translator/benches/bench.rs diff --git a/engine/translator/Cargo.toml b/engine/translator/Cargo.toml index b84cd65..e050ca1 100644 --- a/engine/translator/Cargo.toml +++ b/engine/translator/Cargo.toml @@ -22,3 +22,10 @@ strsim = ["dep:strsim"] rhai = { version = "1.17.0", optional = true, features = ["only_i32", "f32_float", "no_custom_syntax"] } indexmap = { version = "2.2.2", features = ["serde"] } strsim = { version = "0.10.0", optional = true } + +[dev-dependencies] +criterion = "0.5.1" + +[[bench]] +name = "bench" +harness = false diff --git a/engine/translator/benches/bench.rs b/engine/translator/benches/bench.rs new file mode 100644 index 0000000..a4d8bae --- /dev/null +++ b/engine/translator/benches/bench.rs @@ -0,0 +1,71 @@ +#[cfg(feature = "rhai")] +use afrim_translator::Engine; +use afrim_translator::Translator; +use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; +use indexmap::IndexMap; + +pub fn translate(c: &mut Criterion) { + // Generates the dataset. + let mut dictionary = IndexMap::new(); + let words = [ + "Aassiaiel", + "Asiel", + "AazAiel", + "Aziel", + "Aazaryas", + "Uzziah", + "Azaria", + "Aazazya", + "Azaziah", + "Aazraiel", + "Azriel", + "Aebdaiel", + "Abdeel", + ]; + (0..100_000).for_each(|_| { + words.into_iter().for_each(|word| { + dictionary.insert(word.to_owned(), vec![word.to_owned()]); + }); + }); + + // Initializes the translator. + let mut translator = Translator::new(dictionary, false); + + // Registers a translator. + #[cfg(feature = "rhai")] + { + let engine = Engine::new(); + let script = engine + .compile("fn translate(input) { [input, \"\", input, false] }") + .unwrap(); + translator.register("give_back".to_owned(), script); + } + + // Generates candidates for testing. + let mut candidates = Vec::new(); + "Aazraiel".chars().fold("".to_owned(), |word, character| { + let new_word = format!("{word}{character}"); + candidates.push(new_word.clone()); + + new_word + }); + + // Setup the benchmark. + let mut group = c.benchmark_group("translate"); + for candidate in candidates.iter() { + group.bench_with_input( + BenchmarkId::from_parameter(candidate), + candidate, + |b, candidate| { + b.iter(|| { + translator.translate(black_box(candidate)); + }); + }, + ); + } + group.finish(); +} + +criterion_group!(benches, translate); + +criterion_main!(benches);