Skip to content

Commit

Permalink
api: helper for more efficent hash reduction (#1147)
Browse files Browse the repository at this point in the history
  • Loading branch information
brharrington authored Aug 1, 2024
1 parent 355ceab commit 0fe1beb
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
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);
}
}
}

0 comments on commit 0fe1beb

Please sign in to comment.