Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

opt: use gcd to reduce memory overhead #52

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 19 additions & 2 deletions pingora-load-balancing/src/selection/weighted.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@ pub struct Weighted<H = FnvHasher> {
algorithm: H,
}

fn gcd(mut a: usize, mut b: usize) -> usize {
let mut r;
while b != 0 {
r = a % b;
a = b;
b = r;
}
a
}

impl<H: SelectionAlgorithm> BackendSelection for Weighted<H> {
type Iter = WeightedIterator<H>;

Expand All @@ -38,9 +48,16 @@ impl<H: SelectionAlgorithm> BackendSelection for Weighted<H> {
"support up to 2^16 backends"
);
let backends = Vec::from_iter(backends.iter().cloned()).into_boxed_slice();
let mut weighted = Vec::with_capacity(backends.len());
let mut g = 0;
let mut total = 0;
// use gcd to reduce the memory overhead
for (_, b) in backends.iter().enumerate() {
g = gcd(g, b.weight);
total += b.weight;
}
let mut weighted = Vec::with_capacity(total / g);
for (index, b) in backends.iter().enumerate() {
for _ in 0..b.weight {
for _ in 0..(b.weight / g) {
weighted.push(index as u16);
}
}
Expand Down