### Complete Divan Setup Example (Rust & TOML) Source: https://context7.com/nvzqz/divan/llms.txt Example of a complete Divan project setup including Cargo.toml configuration and benchmark definitions in `benches/my_benchmarks.rs`. This demonstrates how to configure dependencies and define benchmark groups with parameterized tests. ```toml # Add to Cargo.toml [dev-dependencies] divan = "0.1.21" [[bench]] name = "my_benchmarks" harness = false ``` ```rust // Create benches/my_benchmarks.rs use divan::{black_box, Bencher}; fn main() { // Run all registered benchmarks divan::main(); } #[divan::bench_group] mod string_ops { use super::*; #[divan::bench(args = [10, 100, 1000])] fn string_concat(n: usize) -> String { let mut result = String::new(); for i in 0..n { result.push_str(&black_box(i).to_string()); } result } #[divan::bench(args = [10, 100, 1000])] fn string_format(bencher: Bencher, n: usize) { bencher.bench(|| { (0..n).map(|i| format!("{}", black_box(i))) .collect::() }); } } // Run with: cargo bench ``` -------------------------------- ### Clone and Benchmark Examples Source: https://github.com/nvzqz/divan/blob/main/README.md This command sequence shows how to clone the Divan repository and run the example benchmarks included within it. This is useful for exploring more advanced usage scenarios. ```sh git clone https://github.com/nvzqz/divan.git cd divan cargo bench -q -p examples --all-features ``` -------------------------------- ### Benchmark with Contextual Setup (Bencher) in Rust Source: https://context7.com/nvzqz/divan/llms.txt Utilizes `Bencher` to set up context before running benchmarks, ensuring setup time is not included in measurements. It demonstrates `bench_local` for setup-only context and `bench` for functions that require setup within the benchmark loop. ```rust use divan::{Bencher, black_box}; fn main() { divan::main(); } #[divan::bench] fn copy_from_slice(bencher: Bencher) { let src = (0..100).collect::>(); let mut dst = vec![0; src.len()]; bencher.bench_local(move || { black_box(&mut dst).copy_from_slice(black_box(&src)); }); } #[divan::bench(args = [0, 5, 10, 20, 30, 40])] fn fibonacci_iterative(bencher: Bencher, n: u64) { bencher.bench(|| { let mut previous = 1; let mut current = 1; for _ in 2..=n { let next = previous + current; previous = current; current = next; } current }); } ``` -------------------------------- ### Control Benchmark Timing with `sample_count`, `sample_size`, and time limits Source: https://context7.com/nvzqz/divan/llms.txt This example demonstrates how to control benchmark timing in Divan using `sample_count`, `sample_size`, `min_time`, and `max_time`. These options allow for precise configuration of how long benchmarks run and how many iterations are performed per sample. `Duration` can be used for more granular time control. Requires `divan` and `black_box`. ```rust use std::time::Duration; use divan::black_box; fn main() { divan::main(); } // Set specific sample count #[divan::bench(sample_count = 1000)] fn fast_operation() -> i32 { black_box(1) + black_box(2) } // Set sample size (iterations per sample) #[divan::bench(sample_size = 10000)] fn very_fast_operation() -> i32 { black_box(5) } // Set time limits #[divan::bench(min_time = 2, max_time = 5)] fn time_limited() -> i32 { black_box(1) * black_box(2) } // Use Duration for precise control #[divan::bench(min_time = Duration::from_secs(3))] fn duration_limited() -> i32 { black_box(10) / black_box(2) } ``` -------------------------------- ### Benchmark Multi-Threaded Performance with `threads` Source: https://context7.com/nvzqz/divan/llms.txt This example illustrates how to benchmark multi-threaded performance using the `threads` option in `divan::bench`. It allows testing contention and parallel execution by specifying a fixed number of threads or a range. Dependencies include `divan`, `Bencher`, and `std::sync::Arc`. ```rust use std::sync::Arc; use divan::Bencher; fn main() { divan::main(); } // Benchmark with default thread count (available parallelism) #[divan::bench(threads)] fn arc_clone(bencher: Bencher) { let arc = Arc::new(42); bencher.bench(|| arc.clone()); } // Benchmark with specific thread count #[divan::bench(threads = 8)] fn arc_clone_8_threads(bencher: Bencher) { let arc = Arc::new(42); bencher.bench(|| arc.clone()); } // Benchmark across multiple thread counts #[divan::bench(threads = [1, 2, 4, 8, 16])] fn arc_clone_scaled(bencher: Bencher) { let arc = Arc::new(42); bencher.bench(|| arc.clone()); } ``` -------------------------------- ### Measure Throughput with BytesCount Source: https://context7.com/nvzqz/divan/llms.txt This example showcases how to measure benchmark throughput using `BytesCount` to track processed bytes. It's useful for understanding the efficiency of string manipulation or data processing operations. The `divan` crate and `Bencher` are necessary, along with the `counter::BytesCount` module. ```rust use divan::{Bencher, counter::BytesCount}; fn main() { divan::main(); } const STR: &str = "The quick brown fox jumps over the lazy dog. Lorem ipsum dolor sit amet, consectetur adipiscing elit."; #[divan::bench(counter = BytesCount::of_str(STR))] fn char_count() -> usize { divan::black_box(STR).chars().count() } const INTS: &[i32] = &[5, 2, 8, 1, 9, 3, 7, 4, 6]; #[divan::bench(counter = BytesCount::of_slice(INTS))] fn slice_sort(bencher: Bencher) { bencher .with_inputs(|| INTS.to_vec()) .bench_refs(|ints| ints.sort()); } ``` -------------------------------- ### Add Divan to Cargo.toml and Create Benchmark File Source: https://github.com/nvzqz/divan/blob/main/README.md This snippet shows how to add Divan as a development dependency in your Cargo.toml file and configure a benchmark target. It also includes a basic example of a benchmarks file (`benches/example.rs`) that registers a function for benchmarking. ```toml [dev-dependencies] divan = "0.1.21" [[bench]] name = "example" harness = false ``` ```rust fn main() { // Run registered benchmarks. divan::main(); } // Register a `fibonacci` function and benchmark it over multiple cases. #[divan::bench(args = [1, 2, 4, 8, 16, 32])] fn fibonacci(n: u64) -> u64 { if n <= 1 { 1 } else { fibonacci(n - 2) + fibonacci(n - 1) } } ``` -------------------------------- ### Benchmark Function with Multiple Arguments in Rust Source: https://context7.com/nvzqz/divan/llms.txt Benchmarks a function across multiple input values using the `args` parameter within the `#[divan::bench]` attribute. The example shows a recursive Fibonacci function benchmarked with various `n` values. ```rust use divan::black_box; fn main() { divan::main(); } #[divan::bench(args = [1, 2, 4, 8, 16, 32])] fn fibonacci(n: u64) -> u64 { if n <= 1 { 1 } else { fibonacci(n - 2) + fibonacci(n - 1) } } // Run with: cargo bench // Output shows timing for each argument value ``` -------------------------------- ### Exclude External Time from Benchmarks (Rust) Source: https://context7.com/nvzqz/divan/llms.txt Benchmark external time exclusion using `skip_ext_time` to isolate timing limits from input generation and drop phases. This ensures that `max_time` only accounts for the function's execution, not setup or teardown. ```rust use divan::Bencher; fn main() { divan::main(); } fn generate_large_input() -> Vec { // Expensive input generation (0..1_000_000).collect() } fn process_data(data: &[i32]) -> i32 { data.iter().sum() } #[divan::bench(max_time = 5, skip_ext_time)] fn with_expensive_setup(bencher: Bencher) { bencher .with_inputs(|| generate_large_input()) .bench_values(|input| process_data(&input)); } // max_time only counts time spent in process_data, // not time spent in generate_large_input or dropping values ``` -------------------------------- ### Run Divan Benchmarks Source: https://github.com/nvzqz/divan/blob/main/README.md This command demonstrates how to execute the benchmarks defined in your project using Cargo. The output shows performance metrics for the `fibonacci` benchmark across different input values. ```text cargo bench ``` -------------------------------- ### Profile Memory Allocations with `AllocProfiler` Source: https://context7.com/nvzqz/divan/llms.txt This snippet shows how to profile memory allocations and deallocations during benchmarks using `AllocProfiler`. It requires setting the global allocator to `AllocProfiler::system()` and using the `types` parameter in `divan::bench` to specify collection types for benchmarking. The output includes detailed allocation statistics. ```rust use divan::{AllocProfiler, Bencher}; use std::collections::{HashSet, LinkedList}; #[global_allocator] static ALLOC: AllocProfiler = AllocProfiler::system(); fn main() { divan::main(); } #[divan::bench(types = [ Vec, LinkedList, HashSet, ])] fn from_iter() -> T where T: FromIterator, { (0..100).collect() } #[divan::bench(types = [ Vec, LinkedList, HashSet, ])] fn drop_collection(bencher: Bencher) where T: FromIterator, { bencher .with_inputs(|| (0..100).collect::()) .bench_values(std::mem::drop); } // Run with: cargo bench // Output includes allocation stats: allocs, deallocs, reallocs, grows, shrinks ``` -------------------------------- ### Baseline Benchmark Comparison in Rust Source: https://github.com/nvzqz/divan/blob/main/WANTED.md This snippet demonstrates how to set up a baseline benchmark in Divan. It uses the `#[divan::bench]` attribute, allowing one benchmark function to be designated as the baseline for another. This is useful for comparing performance changes across different code versions or configurations, ensuring that generic types and constants match. ```rust #[divan::bench] fn old() { ... } #[divan::bench(baseline = old)] fn new() { ... } ``` -------------------------------- ### Basic Benchmark Function in Rust Source: https://context7.com/nvzqz/divan/llms.txt Registers a simple benchmark function using the `#[divan::bench]` attribute. It requires importing `black_box` for accurate measurement and calling `divan::main()` to run the benchmarks. ```rust use divan::black_box; fn main() { divan::main(); } #[divan::bench] fn add() -> i32 { black_box(2) + black_box(1) } #[divan::bench] fn multiply() -> i32 { black_box(2) * black_box(1) } ``` -------------------------------- ### Benchmark Groups with Shared Options in Rust Source: https://context7.com/nvzqz/divan/llms.txt Groups related benchmarks using `#[divan::bench_group]` to share configuration options like `sample_count` and `sample_size`. This promotes code organization and consistent benchmarking parameters for a set of related functions. ```rust use divan::black_box; fn main() { divan::main(); } #[divan::bench_group( sample_count = 100, sample_size = 500, )] mod math { use super::*; #[divan::bench] fn add() -> i32 { black_box(1) + black_box(42) } #[divan::bench] fn div() -> i32 { black_box(1) / black_box(42) } #[divan::bench] fn rem() -> i32 { black_box(42) % black_box(7) } } // Run with: cargo bench ``` -------------------------------- ### Benchmark with Input Generation using `with_inputs` in Rust Source: https://context7.com/nvzqz/divan/llms.txt Employs `with_inputs` to generate fresh inputs for each benchmark iteration, ensuring the generation process is not timed. It showcases `bench_values` for mutable input and `bench_refs` for immutable input references. ```rust use divan::Bencher; fn main() { divan::main(); } const LENS: &[usize] = &[0, 8, 64, 1024]; #[divan::bench(args = LENS)] fn vec_sort(bencher: Bencher, len: usize) { bencher .with_inputs(|| { // Generate input - not timed (0..*len).rev().collect::>() }) .bench_values(|mut vec| { // This is timed vec.sort(); }); } #[divan::bench(args = LENS)] fn vec_sort_unstable(bencher: Bencher, len: usize) { bencher .with_inputs(|| (0..*len).rev().collect::>()) .bench_refs(|vec| { // Benchmarks with mutable reference vec.sort_unstable(); }); } ``` -------------------------------- ### Track Multiple Metrics with `counters` Source: https://context7.com/nvzqz/divan/llms.txt This snippet demonstrates tracking multiple performance metrics simultaneously using the `counters` parameter in `divan::bench`. It combines `BytesCount` and `ItemsCount` to provide a more comprehensive view of benchmark performance. This requires `divan`, `Bencher`, and the respective counter types. ```rust use divan::{Bencher, counter::{BytesCount, ItemsCount}}; fn main() { divan::main(); } const INTS: &[i32] = &[5, 2, 8, 1, 9, 3, 7, 4, 6, 10]; #[divan::bench(counters = [ BytesCount::of_slice(INTS), ItemsCount::new(INTS.len()), ])] fn sort_with_metrics(bencher: Bencher) { bencher .with_inputs(|| INTS.to_vec()) .bench_refs(|ints| ints.sort()); } #[divan::bench(args = [10, 100, 1000])] fn dynamic_counter(bencher: Bencher, len: usize) { bencher .counter(ItemsCount::from(len)) .with_inputs(|| (0..len).collect::>()) .bench_values(|vec| vec.into_iter().sum::()); } ``` -------------------------------- ### Type-Parameterized Benchmarks in Rust Source: https://context7.com/nvzqz/divan/llms.txt Compares performance across different types using the `types` parameter in `#[divan::bench]`. This allows benchmarking the same logic with various data structures or types to identify performance differences. ```rust use divan::{Bencher, black_box}; use std::collections::{BTreeSet, HashSet}; fn main() { divan::main(); } #[divan::bench(types = [&str, String])] fn from_str<'a, T>() -> T where T: From<&'a str>, { black_box("hello world").into() } #[divan::bench( types = [Vec, BTreeSet, HashSet], args = [0, 2, 4, 16, 256, 4096], )] fn from_range(n: i32) -> T where T: FromIterator, { (0..n).collect() } ``` -------------------------------- ### Benchmark with Const Generic Parameters using `consts` Source: https://context7.com/nvzqz/divan/llms.txt This snippet demonstrates how to benchmark functions that utilize const generic parameters. The `consts` option allows specifying an array of values for the generic parameter, enabling benchmarks across different sizes. It requires the `divan` crate and `black_box` for accurate measurement. ```rust use divan::black_box; fn main() { divan::main(); } const SIZES: &[usize] = &[1, 2, 5, 10, 100, 1000]; #[divan::bench(consts = SIZES)] fn init_array() -> [i32; N] { let mut result = [0; N]; for i in 0..N { result[i] = black_box(i as i32); } result } #[divan::bench(consts = SIZES)] fn array_sum() -> i32 { let arr = [1; N]; black_box(&arr).iter().sum() } ``` -------------------------------- ### Conditionally Ignore Benchmarks (Rust) Source: https://context7.com/nvzqz/divan/llms.txt Conditionally ignore benchmarks using the `#[ignore]` attribute or the `ignore` option within the `#[divan::bench]` attribute. Benchmarks can also be ignored based on runtime conditions, such as environment variables. ```rust use divan::black_box; fn main() { divan::main(); } // Using #[ignore] attribute #[divan::bench] #[ignore] fn not_yet_implemented() { unimplemented!(); } // Using ignore option in attribute #[divan::bench(ignore)] fn also_ignored() { unimplemented!(); } // Conditional ignoring based on environment #[divan::bench( ignore = std::env::var("BENCH_EXPENSIVE").as_deref() != Ok("true") )] fn expensive_benchmark() { black_box((0..1_000_000).sum::()); } // Run expensive benchmarks with: BENCH_EXPENSIVE=true cargo bench ``` -------------------------------- ### Prevent Optimizations with Black Box (Rust) Source: https://context7.com/nvzqz/divan/llms.txt Utilize `black_box` to prevent compiler optimizations on benchmark inputs and outputs. This ensures that the compiler does not optimize away operations based on known values, providing more accurate performance measurements. ```rust use divan::black_box; fn main() { divan::main(); } const INDEX: usize = 42; const SLICE: &[u8] = &[1, 2, 3, 4, 5]; #[divan::bench] fn with_black_box_input() -> u8 { // Prevent compiler from optimizing based on known index SLICE[black_box(INDEX % SLICE.len())] } #[divan::bench] fn with_black_box_output() { let result = "hello".to_string(); // Ensure the compiler doesn't optimize away the string creation black_box(result); } #[divan::bench] fn returning_output() -> String { // Returning automatically applies black_box and excludes drop time "world".to_string() } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.