Skip to content
Open
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
30 changes: 19 additions & 11 deletions src/main/java/io/trino/tpcds/distribution/DistributionUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,7 @@ protected static <T> T pickRandomValue(List<T> values, List<Integer> weights, Ra
private static <T> T getValueForWeight(int weight, List<T> values, List<Integer> weights)
{
checkArgument(values.size() == weights.size());
for (int index = 0; index < weights.size(); index++) {
if (weight <= weights.get(index)) {
return values.get(index);
}
}

throw new TpcdsException("random weight was greater than max weight");
return values.get(getIndexForWeight(weight, weights));
}

protected static <T> T getValueForIndexModSize(long index, List<T> values)
Expand All @@ -119,13 +113,27 @@ protected static int pickRandomIndex(List<Integer> weights, RandomNumberStream r

private static int getIndexForWeight(int weight, List<Integer> weights)
{
for (int index = 0; index < weights.size(); index++) {
if (weight <= weights.get(index)) {
return index;
// The weights are prefix sums (monotonically non-decreasing), so the smallest index whose
// cumulative weight is >= the target is a lower-bound binary search. This returns the exact
// same index as a linear scan, including when consecutive weights are equal.
int low = 0;
int high = weights.size() - 1;
int result = -1;
while (low <= high) {

@raunaqmorarka raunaqmorarka Jun 23, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Usually linear scans are faster than binary search for very small lists, does this actually show a gain ?

int mid = (low + high) >>> 1;
if (weight <= weights.get(mid)) {
result = mid;
high = mid - 1;
}
else {
low = mid + 1;
}
}

throw new TpcdsException("random weight was greater than max weight");
if (result == -1) {
throw new TpcdsException("random weight was greater than max weight");
}
return result;
}

protected static int getWeightForIndex(int index, List<Integer> weights)
Expand Down
Loading