Function goose::util::median

source · []
pub fn median(
    btree: &BTreeMap<usize, usize>,
    total_elements: usize,
    min: usize,
    max: usize
) -> usize
Expand description

Calculate median for a BTreeMap of usizes.

The Median is the “middle” of a sorted list of numbers. In this case, the list is comprised of two parts: the integer value on the left, and the number of occurrences of the integer on the right. For example (5, 1) indicates that the integer “5” is included 1 time.

The function requires three parameters that Goose already has while building the BTreeMap: the total occurences of all integers, the smallest integer, and the largest integer in the list: while this could be calculate by the function, the goal is to make this function as fast as possible as it runs during load tests.

NOTE: Once first_entry and last_entry land in Stable Rust (rust-lang issue #62924) we can efficiently derive the last two parameters and simplify the calling of this function a little.

Example

use std::collections::BTreeMap;
use goose::util;

// In this first example, we add one instance of three different integers.
let mut btree: BTreeMap<usize, usize> = BTreeMap::new();
btree.insert(1, 1);
btree.insert(99, 1);
btree.insert(100, 1);

// Median (middle) value in this list of 3 integers is 99.
assert_eq!(util::median(&btree, 3, 1, 100), 99);

// In this next example, we add multiple instance of five different integers.
let mut btree: BTreeMap<usize, usize> = BTreeMap::new();
btree.insert(7, 5);
btree.insert(8, 1);
btree.insert(13, 21);
btree.insert(19, 44);
btree.insert(21, 5);

// Median (middle) value in this list of 76 integers is 19.
assert_eq!(util::median(&btree, 76, 7, 21), 19);