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

api: helper for more efficient hash reduction #1147

Merged
merged 1 commit into from
Aug 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions spectator-api/src/main/java/com/netflix/spectator/impl/Hash64.java
Original file line number Diff line number Diff line change
Expand Up @@ -414,4 +414,22 @@ public long computeAndReset() {
reset();
return h;
}

/**
* Helper to efficiently reduce hash from to range of {@code [0, n)}. Based on
* <a href="https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/">fast
* alternative to modulo reduction</a> post.
*/
public static int reduce(long hash, int n) {
return reduce((int) hash, n);
}

/**
* Helper to efficiently reduce hash from to range of {@code [0, n)}. Based on
* <a href="https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/">fast
* alternative to modulo reduction</a> post.
*/
public static int reduce(int hash, int n) {
return (int) (((hash & 0xFFFFFFFFL) * (n & 0xFFFFFFFFL)) >>> 32);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -272,4 +272,19 @@ public void hashDoubles() {
hashes.add(h);
}
}

@Test
public void reduce() {
int n = 10;
int[] counts = new int[n];
Random r = new Random();
for (int i = 0; i < 100_000; ++i) {
long hash = r.nextLong();
++counts[Hash64.reduce(hash, n)];
}
for (int count : counts) {
int delta = Math.abs(10_000 - count);
Assertions.assertTrue(delta < 1000);
}
}
}
Loading