### Write and Read HDRHistogram Interval Logs in Rust Source: https://context7.com/hdrhistogram/hdrhistogram_rust/llms.txt Shows how to write interval logs with comments, start times, base times, and optional tags, and how to parse these logs using an iterator. ```rust use std::time::{Duration, SystemTime}; use hdrhistogram::Histogram; use hdrhistogram::serialization::{V2Serializer, Deserializer}; use hdrhistogram::serialization::interval_log:: IntervalLogWriterBuilder, IntervalLogIterator, LogEntry, Tag // Write an interval log let mut buf = Vec::new(); let mut serializer = V2Serializer::new(); let now = SystemTime::now(); { let mut log_writer = IntervalLogWriterBuilder::new() .add_comment("Performance test results") .with_start_time(now) .with_base_time(now) .with_max_value_divisor(1_000_000.0) // Convert ns to ms .begin_log_with(&mut buf, &mut serializer) .expect("create log writer"); // Write histogram intervals (simulating periodic captures) for i in 0..5 { let mut h = Histogram::::new_with_bounds(1, u64::max_value(), 3).unwrap(); h.record((i + 1) * 1000).unwrap(); log_writer.write_histogram( &h, Duration::from_secs(i), // Start timestamp Duration::from_secs(1), // Duration Tag::new("latency") // Optional tag ).expect("write histogram"); } } println!("Log content:\n{}", String::from_utf8_lossy(&buf)); // Parse an interval log let log_data = b"#Test log\nTag=api,0.127,1.007,2.769,HISTFAAAB\n1.456,1.007,2.769,HISTFAAAC\n"; let iter = IntervalLogIterator::new(&log_data[..]); for entry in iter { match entry { Ok(LogEntry::Interval(h)) => { println!("Interval: start={:?}, duration={:?}, tag={:?}", h.start_timestamp(), h.duration(), h.tag().map(|t| t.as_str())); // Decode histogram: base64::decode(h.encoded_histogram()) } Ok(LogEntry::StartTime(t)) => println!("StartTime: {:?}", t), Ok(LogEntry::BaseTime(t)) => println!("BaseTime: {:?}", t), Err(e) => eprintln!("Parse error: {:?}", e), } } ``` -------------------------------- ### Get HDR Histogram Statistics Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/tests/data/seq-nums.txt Shows how to retrieve various statistical information from an HDR histogram, such as count, mean, min, max, and percentiles. These statistics are useful for understanding data distribution. ```rust use hdrhistogram::Histogram; fn main() { let mut histogram = Histogram::::new_with_bounds(1, 100_000, 3).unwrap(); histogram.record(100).unwrap(); histogram.record(500).unwrap(); histogram.record(1000).unwrap(); histogram.record(2500).unwrap(); histogram.record(5000).unwrap(); // Get basic statistics. println!("Count: {}", histogram.len()); println!("Min: {}", histogram.min()); println!("Max: {}", histogram.max()); println!("Mean: {:.2}", histogram.mean()); // Get percentile values. println!("50th percentile (median): {}", histogram.value_at_quantile(0.5)); println!("90th percentile: {}", histogram.value_at_quantile(0.9)); println!("99th percentile: {}", histogram.value_at_quantile(0.99)); println!("99.9th percentile: {}", histogram.value_at_quantile(0.999)); } ``` -------------------------------- ### Create HdrHistograms with Different Configurations Source: https://context7.com/hdrhistogram/hdrhistogram_rust/llms.txt Demonstrates creating histograms using different constructors for auto-resizing, fixed bounds, fixed maximum, and smaller counter types. Also shows how to enable auto-resize and clone histogram configurations. ```rust use hdrhistogram::Histogram; // Auto-resizing histogram with 3 significant figures precision let mut hist = Histogram::::new(3).unwrap(); // Fixed range histogram: tracks values 1 to 3,600,000 with 2 sigfig precision // Useful for tracking latencies from 1µs to 1 hour with 1% precision let mut latency_hist = Histogram::::new_with_bounds(1, 3_600_000, 2).unwrap(); // Fixed maximum histogram: tracks values up to 10,000 with 3 sigfig precision let mut bounded_hist = Histogram::::new_with_max(10_000, 3).unwrap(); // Use smaller counter types to reduce memory when overflow is not a concern let mut compact_hist = Histogram::::new(2).unwrap(); // Enable auto-resize on an existing histogram latency_hist.auto(true); // Create histogram with same configuration as another let cloned_config = Histogram::::new_from(&latency_hist); ``` -------------------------------- ### Create and Populate HDR Histogram Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/tests/data/seq-nums.txt Demonstrates how to create a new HDR histogram with specified precision and add recorded values. Ensure the histogram is initialized before recording values. ```rust use hdrhistogram::Histogram; fn main() { // Create a histogram with a precision of 3 decimal places (e.g., 1000 units per integer count). // The range is from 0 to 3600000000000 (3.6e12). let mut histogram = Histogram::::new_with_bounds(0, 3_600_000_000_000, 3).unwrap(); // Record some values. histogram.record(100_000_000).unwrap(); histogram.record(500_000_000).unwrap(); histogram.record(1_000_000_000).unwrap(); // You can now query the histogram for statistics. println!("Count: {}", histogram.count()); println!("Min: {}", histogram.min().unwrap_or(0)); println!("Max: {}", histogram.max().unwrap_or(0)); println!("Mean: {:.2}", histogram.mean()); println!("Median (50th percentile): {}", histogram.value_at_quantile(0.5)); println!("99th percentile: {}", histogram.value_at_quantile(0.99)); } ``` -------------------------------- ### Query HDRHistogram for Statistics Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/README.md Shows how to initialize a Histogram and retrieve basic statistics like the total number of samples and the value at a specific quantile. ```rust use hdrhistogram::Histogram; let hist = Histogram::::new(2).unwrap(); // ... println!("# of samples: {}", hist.len()); println!( ``` ```rust println!("99.9'th percentile: {}", hist.value_at_quantile(0.999)); ``` -------------------------------- ### Create and Record Samples in HDRHistogram Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/README.md Demonstrates creating a Histogram with specified bounds and precision, and recording samples using `.record()` and `+=`. The `+=` operator panics on out-of-range values. ```rust use hdrhistogram::Histogram; let mut hist = Histogram::::new_with_bounds(1, 60 * 60 * 1000, 2).unwrap(); // samples can be recorded using .record, which will error if the value is too small or large hist.record(54321).expect("value 54321 should be in range"); // for ergonomics, samples can also be recorded with += // this call will panic if the value is out of range! hist += 54321; // if the code that generates the values is subject to Coordinated Omission, // the self-correcting record method should be used instead. // for example, if the expected sampling interval is 10 msec: hist.record_correct(54321, 10).expect("value 54321 should be in range"); ``` -------------------------------- ### Create and Record HDR Histogram Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/tests/data/seq-nums.txt Demonstrates how to create a new HDR histogram with specified precision and record values. Ensure the histogram is configured with appropriate precision for your data range. ```rust use hdrhistogram::Histogram; fn main() { // Create a histogram with a precision of 3 decimal places (1000 units per integer). // The maximum value is set to 100,000. let mut histogram = Histogram::::new_with_bounds(1, 100_000, 3).unwrap(); // Record some values. histogram.record(100).unwrap(); histogram.record(500).unwrap(); histogram.record(1000).unwrap(); println!("Histogram created and values recorded."); } ``` -------------------------------- ### Iterate Through HDR Histogram Buckets Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/tests/data/seq-nums.txt Demonstrates how to iterate through the recorded values and their counts within an HDR histogram. This allows for detailed inspection of the distribution. ```rust use hdrhistogram::Histogram; fn main() { let mut histogram = Histogram::::new_with_bounds(1, 100_000, 3).unwrap(); histogram.record(100).unwrap(); histogram.record(100).unwrap(); histogram.record(500).unwrap(); histogram.record(1000).unwrap(); // Iterate through the histogram's recorded values and counts. for (value, count) in histogram.iter() { println!("Value: {}, Count: {}", value, count); } } ``` -------------------------------- ### Add HdrHistogram dependency Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/README.md Include the crate in your Cargo.toml file. ```toml [dependencies] hdrhistogram = "7" ``` -------------------------------- ### Query Value Equivalence and Resolution Source: https://context7.com/hdrhistogram/hdrhistogram_rust/llms.txt Determine how values map to buckets and check for equivalence between values. These methods help understand the precision and resolution characteristics of the configured histogram. ```rust use hdrhistogram::Histogram; let hist = Histogram::::new_with_bounds(1, 3_600_000, 2).unwrap(); let value = 12345; // Get the range of equivalent values let lowest = hist.lowest_equivalent(value); let highest = hist.highest_equivalent(value); let median = hist.median_equivalent(value); let range = hist.equivalent_range(value); let next = hist.next_non_equivalent(value); println!("For value {}:", value); println!(" Lowest equivalent: {}", lowest); println!(" Highest equivalent: {}", highest); println!(" Median equivalent: {}", median); println!(" Equivalent range: {}", range); println!(" Next non-equivalent: {}", next); // Check if two values are equivalent (map to same bucket) let are_equiv = hist.equivalent(12340, 12350); println!(" 12340 ≡ 12350: {}", are_equiv); // Histogram configuration info println!("\nHistogram info:"); println!(" Distinct values (buckets): {}", hist.distinct_values()); println!(" Bucket count: {}", hist.buckets()); println!(" Auto-resize enabled: {}", hist.is_auto_resize()); ``` -------------------------------- ### Querying Histogram Statistics Source: https://context7.com/hdrhistogram/hdrhistogram_rust/llms.txt Calculate percentiles, quantiles, mean, standard deviation, and value counts from a populated histogram. ```rust use hdrhistogram::Histogram; let mut hist = Histogram::::new(3).unwrap(); for i in 1..=10000 { hist += i; } // Get value at specific quantile (0.0 to 1.0) let p50 = hist.value_at_quantile(0.5); let p99 = hist.value_at_quantile(0.99); let p999 = hist.value_at_quantile(0.999); let p9999 = hist.value_at_quantile(0.9999); // Get value at percentile (0 to 100) let p95 = hist.value_at_percentile(95.0); println!("p50: {}, p95: {}, p99: {}, p99.9: {}, p99.99: {}", p50, p95, p99, p999, p9999); // Statistical measures println!("Mean: {:.2}", hist.mean()); println!("StdDev: {:.2}", hist.stdev()); println!("Min: {}, Max: {}", hist.min(), hist.max()); println!("Min non-zero: {}", hist.min_nz()); // Get quantile of values at or below a given value let quantile = hist.quantile_below(5000); let percentile = hist.percentile_below(5000); println!("Quantile below 5000: {:.4} ({:.2}%)", quantile, percentile); // Count values in a range or at a specific value let count_in_range = hist.count_between(1000, 2000); let count_at_value = hist.count_at(5000); println!("Count between 1000-2000: {}", count_in_range); println!("Count at 5000: {}", count_at_value); ``` -------------------------------- ### Create HDRHistogram with Specific Precision in Rust Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/tests/data/seq-nums.txt Shows how to create an HDRHistogram with a specified number of decimal places for precision. This allows for finer-grained measurements when needed. ```rust use hdrhistogram::Histogram; fn main() { // Create a histogram with a maximum value of 10000 and 5 decimal places of precision. let mut histogram = Histogram::::new_with_precision(1, 10000, 5).unwrap(); histogram.record(12345).unwrap(); println!("Recorded value: {}", histogram.recorded_values().next().unwrap()); } ``` -------------------------------- ### Perform Multi-threaded Recording with SyncHistogram Source: https://context7.com/hdrhistogram/hdrhistogram_rust/llms.txt Use SyncHistogram and Recorder for wait-free, concurrent recording from multiple threads. Recorders automatically sync on drop, and refresh() must be called to merge data into the main histogram. ```rust use hdrhistogram::Histogram; use hdrhistogram::sync::SyncHistogram; use std::thread; use std::time::Duration; // Create a SyncHistogram from a regular histogram let hist = Histogram::::new_with_bounds(1, 60_000, 3).unwrap(); let mut sync_hist: SyncHistogram = hist.into_sync(); // Spawn multiple recording threads let mut handles = vec![]; for thread_id in 0..4 { let mut recorder = sync_hist.recorder(); handles.push(thread::spawn(move || { for i in 0..1000 { recorder.record((thread_id + 1) as u64 * 100 + i).unwrap(); } // Recorder automatically syncs on drop })); } // Wait for threads to complete for handle in handles { handle.join().unwrap(); } // Refresh to merge all recorder data into the main histogram sync_hist.refresh(); // Now query the merged results println!("Total samples: {}", sync_hist.len()); // 4000 println!("Mean: {:.2}", sync_hist.mean()); println!("p99: {}", sync_hist.value_at_quantile(0.99)); // Can also use refresh with timeout sync_hist.refresh_timeout(Duration::from_millis(100)); // Mark a recorder as idle when it won't record for a while let mut recorder = sync_hist.recorder(); { let _idle_guard = recorder.idle(); // Recorder is idle, won't block refresh() thread::sleep(Duration::from_millis(10)); } // Guard dropped, recorder active again recorder += 42; ``` -------------------------------- ### Import HdrHistogram in crate root Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/README.md Add the extern crate declaration to your project's root module. ```rust extern crate hdrhistogram; ``` -------------------------------- ### Iterate Recorded Samples in HDRHistogram Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/README.md Demonstrates iterating through recorded sample bins in a Histogram to access percentile, value, and count information for each bin. ```rust use hdrhistogram::Histogram; let hist = Histogram::::new(2).unwrap(); // ... for v in hist.iter_recorded() { println!("{}'th percentile of data is {} with {} samples", v.percentile(), v.value_iterated_to(), v.count_at_value()); } ``` -------------------------------- ### Create and Record in HDRHistogram Rust Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/tests/data/seq-nums.txt Demonstrates the basic creation and recording of values into an HDRHistogram. Ensure the histogram is configured with appropriate precision and bounds for your data. ```rust use hdrhistogram::Histogram; fn main() { // Create a histogram with a maximum value of 1000 and 3 decimal places of precision. let mut histogram = Histogram::::new(1, 1000).unwrap(); // Record some values. histogram.record(10).unwrap(); histogram.record(500).unwrap(); histogram.record(999).unwrap(); // You can now query statistics from the histogram. println!("Count: {}", histogram.count()); println!("Mean: {}", histogram.mean()); println!("Max: {}", histogram.max()); } ``` -------------------------------- ### Merge HDR Histograms Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/tests/data/seq-nums.txt Illustrates how to merge two HDR histograms into a single one. This is useful when aggregating results from multiple sources. ```rust use hdrhistogram::Histogram; fn main() { let mut histogram1 = Histogram::::new_with_bounds(1, 100_000, 3).unwrap(); histogram1.record(100).unwrap(); histogram1.record(500).unwrap(); let mut histogram2 = Histogram::::new_with_bounds(1, 100_000, 3).unwrap(); histogram2.record(200).unwrap(); histogram2.record(600).unwrap(); // Merge histogram2 into histogram1. histogram1.add(&histogram2).unwrap(); println!("Histograms merged. Total count: {}", histogram1.len()); println!("50th percentile after merge: {}", histogram1.value_at_quantile(0.5)); } ``` -------------------------------- ### Merge HDR Histograms Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/tests/data/seq-nums.txt Illustrates how to merge two HDR histograms into one. This is useful when aggregating results from multiple sources. The histograms must have compatible bounds and precision. ```rust use hdrhistogram::Histogram; fn main() { let mut histogram1 = Histogram::::new_with_bounds(0, 1000, 3).unwrap(); histogram1.record(10).unwrap(); histogram1.record(50).unwrap(); let mut histogram2 = Histogram::::new_with_bounds(0, 1000, 3).unwrap(); histogram2.record(20).unwrap(); histogram2.record(60).unwrap(); // Merge histogram2 into histogram1. histogram1.merge(&histogram2).unwrap(); println!("Merged count: {}", histogram1.count()); println!("Merged 50th percentile: {}", histogram1.value_at_quantile(0.5)); } ``` -------------------------------- ### Iterate Over Histogram Records Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/tests/data/seq-nums.txt Shows how to iterate through the recorded values in an HDR histogram. This can be useful for custom analysis or debugging. Note that iteration order is not guaranteed. ```rust use hdrhistogram::Histogram; fn main() { let mut histogram = Histogram::::new_with_bounds(0, 1000, 3).unwrap(); histogram.record(10).unwrap(); histogram.record(50).unwrap(); histogram.record(100).unwrap(); println!("Iterating over recorded values:"); for value in histogram.iter_recorded() { println!("{}", value); } } ``` -------------------------------- ### Iterating Through Histogram Data Source: https://context7.com/hdrhistogram/hdrhistogram_rust/llms.txt Traverse histogram data using various strategies including recorded values, linear steps, logarithmic steps, and quantiles. ```rust use hdrhistogram::Histogram; let mut hist = Histogram::::new_with_max(10000, 3).unwrap(); for i in [100, 500, 800, 850, 1000, 5000] { hist += i; } // Iterate over all recorded (non-zero) values println!("Recorded values:"); for v in hist.iter_recorded() { println!(" Value: {}, Count: {}, Percentile: {:.2}%", v.value_iterated_to(), v.count_at_value(), v.percentile()); } // Iterate with linear value steps (every 1000 units) println!("\nLinear iteration (step=1000):"); for v in hist.iter_linear(1000) { if v.count_since_last_iteration() > 0 { println!(" Up to {}: {} samples", v.value_iterated_to(), v.count_since_last_iteration()); } } // Iterate with logarithmic steps (start=1, multiply by 10 each step) println!("\nLogarithmic iteration:"); for v in hist.iter_log(1, 10.0) { println!(" Up to {}: {} samples", v.value_iterated_to(), v.count_since_last_iteration()); } // Iterate by quantiles (ticks_per_half_distance controls granularity) println!("\nQuantile iteration:"); for v in hist.iter_quantiles(5) { println!(" Quantile {:.4}: value={}", v.quantile_iterated_to(), v.value_iterated_to()); } // Iterate over all possible values (including zeros) let small_hist = Histogram::::new_with_max(10, 1).unwrap(); for v in small_hist.iter_all() { println!(" Value {}: count {}", v.value_iterated_to(), v.count_at_value()); } ``` -------------------------------- ### HDR Histogram with Different Integer Types Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/tests/data/seq-nums.txt Shows the flexibility of the HDR Histogram crate by using different integer types for recording values. The chosen type should accommodate the expected range of measurements. ```rust use hdrhistogram::Histogram; fn main() { // Using u32 for values, with bounds up to 1,000,000. let mut histogram_u32 = Histogram::::new_with_bounds(1, 1_000_000, 3).unwrap(); histogram_u32.record(1000).unwrap(); println!("Histogram with u32: Count = {}", histogram_u32.len()); // Using u64 for values, with bounds up to 10^18. let mut histogram_u64 = Histogram::::new_with_bounds(1, 1_000_000_000_000_000_000, 3).unwrap(); histogram_u64.record(500_000_000_000).unwrap(); println!("Histogram with u64: Count = {}", histogram_u64.len()); } ``` -------------------------------- ### Iterate Over HDRHistogram Buckets in Rust Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/tests/data/seq-nums.txt Shows how to iterate over the recorded values in an HDRHistogram using its bucket iterator. This is useful for understanding the distribution of recorded data. ```rust use hdrhistogram::Histogram; fn main() { let mut histogram = Histogram::::new(1, 1000).unwrap(); histogram.record(10).unwrap(); histogram.record(500).unwrap(); histogram.record(999).unwrap(); // Iterate over the buckets. for bucket in histogram.iter_recorded() { println!("Bucket: count={}, low={}, high={}", bucket.count, bucket.low, bucket.high); } } ``` -------------------------------- ### Merge HDRHistograms in Rust Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/tests/data/seq-nums.txt Demonstrates how to merge two HDRHistograms into one. This is useful when aggregating results from multiple sources. ```rust use hdrhistogram::Histogram; fn main() { let mut h1 = Histogram::::new(1, 1000).unwrap(); h1.record(10).unwrap(); h1.record(50).unwrap(); let mut h2 = Histogram::::new(1, 1000).unwrap(); h2.record(20).unwrap(); h2.record(60).unwrap(); // Merge h2 into h1. h1.add(&h2).unwrap(); println!("Merged count: {}", h1.count()); // Should be 4 println!("Merged max: {}", h1.max()); // Should be 60 } ``` -------------------------------- ### Performing Histogram Arithmetic Source: https://context7.com/hdrhistogram/hdrhistogram_rust/llms.txt Aggregate, subtract, and merge histograms, including support for coordinated omission correction. ```rust use hdrhistogram::Histogram; let mut hist1 = Histogram::::new(3).unwrap(); let mut hist2 = Histogram::::new(3).unwrap(); for i in 1..=100 { hist1 += i; } for i in 50..=150 { hist2 += i; } // Add histograms (with error handling) hist1.add(&hist2).expect("add should succeed"); // Operator syntax (panics on error) let mut combined = Histogram::::new(3).unwrap(); combined += &hist1; combined += hist2.clone(); // Create new histogram from addition let sum_hist = hist1.clone() + &hist2; // Subtract histograms let mut minuend = Histogram::::new(3).unwrap(); let mut subtrahend = Histogram::::new(3).unwrap(); for i in 1..=100 { minuend += i; } for i in 1..=50 { subtrahend += i; } minuend.subtract(&subtrahend).expect("subtract should succeed"); println!("After subtraction, count: {}", minuend.len()); // 50 // Sum multiple histograms using iterator let histograms: Vec> = (0..5).map(|_| { let mut h = Histogram::new(3).unwrap(); h += 100; h }).collect(); let total: Histogram = histograms.into_iter().sum(); println!("Total count from 5 histograms: {}", total.len()); // 5 // Add with coordinated omission correction let mut corrected = Histogram::::new(3).unwrap(); corrected.add_correct(&hist1, 10).expect("add_correct should succeed"); ``` -------------------------------- ### HDR Histogram with Different Value Types Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/tests/data/seq-nums.txt Shows the flexibility of HDR Histogram by using different integer types for recording values. Ensure the chosen type can accommodate the expected range of values. ```rust use hdrhistogram::Histogram; fn main() { // Using u32 for values let mut histogram_u32 = Histogram::::new_with_bounds(0, 1000, 3).unwrap(); histogram_u32.record(100).unwrap(); histogram_u32.record(500).unwrap(); println!("Histogram with u32 count: {}", histogram_u32.count()); // Using u64 for values let mut histogram_u64 = Histogram::::new_with_bounds(0, 1_000_000_000_000, 3).unwrap(); histogram_u64.record(100_000_000_000).unwrap(); histogram_u64.record(500_000_000_000).unwrap(); println!("Histogram with u64 count: {}", histogram_u64.count()); } ``` -------------------------------- ### Serialize and Deserialize HDRHistogram in Rust Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/tests/data/seq-nums.txt Illustrates how to serialize and deserialize an HDRHistogram to and from a byte vector using the `serde` crate. This is useful for saving and loading histogram state. ```rust use hdrhistogram::Histogram; use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize)] struct MyData { histogram: Histogram, } fn main() { let mut histogram = Histogram::::new(1, 1000).unwrap(); histogram.record(10).unwrap(); let data = MyData { histogram }; // Serialize to JSON let json = serde_json::to_string(&data).unwrap(); println!("Serialized: {}", json); // Deserialize from JSON let deserialized_data: MyData = serde_json::from_str(&json).unwrap(); println!("Deserialized count: {}", deserialized_data.histogram.count()); } ``` -------------------------------- ### Apply Coordinated Omission Correction in HdrHistogram Source: https://context7.com/hdrhistogram/hdrhistogram_rust/llms.txt Demonstrates how to use `record_correct` and `record_n_correct` to account for missed samples in latency measurements. Also shows creating a corrected copy of an existing histogram. ```rust use hdrhistogram::Histogram; let mut hist = Histogram::::new_with_bounds(1, 60_000, 2).unwrap(); // Expected sampling interval is 10ms let interval = 10; // Record with coordinated omission correction // If value=50, adds samples at 50, 40, 30, 20 (down to interval) hist.record_correct(54, interval).expect("recording should succeed"); // Record multiple occurrences with correction hist.record_n_correct(100, 5, interval).expect("recording should succeed"); // Create a corrected copy of an existing histogram (post-correction) let uncorrected = { let mut h = Histogram::::new(3).unwrap(); h.record(100).unwrap(); h.record(200).unwrap(); h }; let corrected = uncorrected.clone_correct(interval); println!("Original count: {}, Corrected count: 2", uncorrected.len()); ``` -------------------------------- ### Serialize and Deserialize HDR Histogram Source: https://github.com/hdrhistogram/hdrhistogram_rust/blob/main/tests/data/seq-nums.txt Demonstrates how to serialize an HDR histogram to a byte vector and deserialize it back. This is useful for saving and loading histogram state. Ensure the data is valid before deserializing. ```rust use hdrhistogram::Histogram; fn main() { let mut histogram = Histogram::::new_with_bounds(0, 1000, 3).unwrap(); histogram.record(10).unwrap(); histogram.record(50).unwrap(); // Serialize the histogram to a byte vector. let mut buffer = Vec::new(); histogram.encode(&mut buffer).unwrap(); // Deserialize the histogram from the byte vector. let decoded_histogram = Histogram::decode(&buffer[..]).unwrap(); println!("Original count: {}", histogram.count()); println!("Decoded count: {}", decoded_histogram.count()); println!("Decoded 50th percentile: {}", decoded_histogram.value_at_quantile(0.5)); } ``` -------------------------------- ### Record Values in HdrHistogram Source: https://context7.com/hdrhistogram/hdrhistogram_rust/llms.txt Shows how to record single values, multiple occurrences of a value, and use saturating record methods that clamp values to the histogram's range. Includes checks for histogram state. ```rust use hdrhistogram::Histogram; let mut hist = Histogram::::new_with_bounds(1, 60_000, 2).unwrap(); // Record a single value (returns error if out of range and resize disabled) hist.record(1234).expect("value should be in range"); // Ergonomic recording using += operator (panics on error) hist += 5678; // Record multiple occurrences of the same value hist.record_n(100, 50).expect("record 50 occurrences of value 100"); // Saturating record: clamps value to range, never fails hist.saturating_record(999_999_999); // Clamped to 60_000 (max) hist.saturating_record(0); // Clamped to 1 (min) // Record multiple values with saturation hist.saturating_record_n(50_000, 10); // Check histogram state println!("Total samples: {}", hist.len()); println!("Is empty: {}", hist.is_empty()); println!("Lowest trackable: {}", hist.low()); println!("Highest trackable: {}", hist.high()); println!("Significant figures: {}", hist.sigfig()); ``` -------------------------------- ### Handle HDRHistogram Creation Errors Source: https://context7.com/hdrhistogram/hdrhistogram_rust/llms.txt Catch specific creation errors like LowIsZero, HighLessThanTwiceLow, and SigFigExceedsMax when initializing a histogram. Ensure valid bounds and significant figures are provided. ```rust use hdrhistogram::Histogram; use hdrhistogram::errors::CreationError; // Creation errors match Histogram::::new_with_bounds(0, 100, 3) { Err(CreationError::LowIsZero) => println!("Low must be >= 1"), _ => {} } match Histogram::::new_with_bounds(1, 1, 3) { Err(CreationError::HighLessThanTwiceLow) => println!("High must be >= 2 * low"), _ => {} } match Histogram::::new(6) { Err(CreationError::SigFigExceedsMax) => println!("Sigfig must be <= 5"), _ => {} } ``` -------------------------------- ### Serialize and Deserialize HDRHistograms in Rust Source: https://context7.com/hdrhistogram/hdrhistogram_rust/llms.txt Demonstrates serializing histograms to V2 and V2+DEFLATE formats and deserializing them. Supports serializing multiple histograms to a single buffer. ```rust use hdrhistogram::Histogram; use hdrhistogram::serialization::{Deserializer, Serializer, V2Serializer, V2DeflateSerializer}; use std::io::Cursor; let mut hist = Histogram::::new_with_bounds(1, u64::max_value(), 3).unwrap(); for i in 1..=10000 { hist += i * i; } // Serialize to V2 format (uncompressed) let mut buf = Vec::new(); V2Serializer::new().serialize(&hist, &mut buf).expect("serialize should succeed"); println!("V2 serialized size: {} bytes", buf.len()); // Serialize to V2+DEFLATE format (compressed) let mut compressed_buf = Vec::new(); V2DeflateSerializer::new() .serialize(&hist, &mut compressed_buf) .expect("compressed serialize should succeed"); println!("V2+DEFLATE serialized size: {} bytes", compressed_buf.len()); // Deserialize (auto-detects format) let restored: Histogram = Deserializer::new() .deserialize(&mut buf.as_slice()) .expect("deserialize should succeed"); assert_eq!(hist.len(), restored.len()); assert_eq!(hist.max(), restored.max()); // Serialize multiple histograms to same buffer let mut multi_buf = Vec::new(); let mut serializer = V2Serializer::new(); for _ in 0..3 { let mut h = Histogram::::new(2).unwrap(); h.record_n(42, 7).unwrap(); serializer.serialize(&h, &mut multi_buf).expect("serialize"); } // Deserialize multiple histograms let mut cursor = Cursor::new(&multi_buf); let mut deserializer = Deserializer::new(); let mut total_count = 0u64; for _ in 0..3 { let h: Histogram = deserializer.deserialize(&mut cursor).expect("deserialize"); total_count += h.len(); } println!("Total count from 3 histograms: {}", total_count); // 21 ``` -------------------------------- ### Reset and Clear Histogram Data Source: https://context7.com/hdrhistogram/hdrhistogram_rust/llms.txt Clear counts while preserving configuration or perform a full reset of statistics. Data can also be copied between histograms using set_to or set_to_corrected. ```rust use hdrhistogram::Histogram; let mut hist = Histogram::::new_with_bounds(1, 10_000, 3).unwrap(); for i in 1..=1000 { hist += i; } println!("Before clear - Count: {}, Max: {}", hist.len(), hist.max()); // Clear counts but preserve configuration hist.clear(); println!("After clear - Count: {}, Max: {}", hist.len(), hist.max()); // Record again for i in 1..=500 { hist += i; } println!("After re-recording - Count: {}, Max: {}", hist.len(), hist.max()); // Full reset: clears counts AND resets min/max statistics hist.reset(); println!("After reset - Count: {}, is_empty: {}", hist.len(), hist.is_empty()); // Copy another histogram's data into this one let mut source = Histogram::::new(3).unwrap(); source += 42; source += 100; hist.set_to(&source).expect("set_to should succeed"); println!("After set_to - Count: {}, Max: {}", hist.len(), hist.max()); // Copy with coordinated omission correction hist.set_to_corrected(&source, 10).expect("set_to_corrected should succeed"); ``` -------------------------------- ### Handle HDRHistogram Recording Errors Source: https://context7.com/hdrhistogram/hdrhistogram_rust/llms.txt Manage recording errors, specifically ValueOutOfRangeResizeDisabled, when auto-resize is off. Use saturating_record as an alternative to clamp values within the histogram's range. ```rust use hdrhistogram::Histogram; use hdrhistogram::errors::RecordError; // Recording errors (when auto-resize is disabled) let mut hist = Histogram::::new_with_max(100, 3).unwrap(); match hist.record(200) { Err(RecordError::ValueOutOfRangeResizeDisabled) => { println!("Value 200 exceeds max 100"); // Use saturating_record as alternative hist.saturating_record(200); // Records as 100 } Ok(()) => {} Err(e) => println!("Other error: {:?}", e), } ``` -------------------------------- ### Handle HDRHistogram Addition Errors Source: https://context7.com/hdrhistogram/hdrhistogram_rust/llms.txt Detect and handle AdditionError::OtherAddendValueExceedsRange when attempting to add two histograms where the source histogram's values exceed the target histogram's range. ```rust use hdrhistogram::Histogram; use hdrhistogram::errors::AdditionError; // Addition errors let mut small = Histogram::::new_with_max(100, 3).unwrap(); let mut large = Histogram::::new(3).unwrap(); large += 1000; match small.add(&large) { Err(AdditionError::OtherAddendValueExceedsRange) => { println!("Cannot add: source values exceed target range"); } Ok(()) => {} Err(e) => println!("Other error: {:?}", e), } ``` -------------------------------- ### Handle HDRHistogram Subtraction Errors Source: https://context7.com/hdrhistogram/hdrhistogram_rust/llms.txt Manage SubtractionError::SubtrahendCountExceedsMinuendCount when subtracting histograms, which occurs if the subtrahend's counts would result in negative values for the minuend. ```rust use hdrhistogram::Histogram; use hdrhistogram::errors::SubtractionError; // Subtraction errors let mut minuend = Histogram::::new(3).unwrap(); let mut subtrahend = Histogram::::new(3).unwrap(); minuend += 100; subtrahend.record_n(100, 5).unwrap(); match minuend.subtract(&subtrahend) { Err(SubtractionError::SubtrahendCountExceedsMinuendCount) => { println!("Cannot subtract: would result in negative count"); } Ok(()) => {} Err(e) => println!("Other error: {:?}", e), } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.