Skip to content

HistogramBase.GetValueAtPercentile — Double-Loop When Flat Array Index Is Available #145

Description

@leecampbell-codeagent

File: HistogramBase.cs

The percentile lookup iterates nested i / j loops over BucketCount × SubBucketCount. Since CountsArrayIndex(bucketIndex, subBucketIndex) maps this to a flat array, and the counts array is already flat in LongHistogram, the entire scan can be done as a single flat loop:

public long GetValueAtPercentile(double percentile)
{
    var countAtPercentile = Math.Max(
        (long)((Math.Min(percentile, 100.0) / 100.0 * TotalCount) + 0.5), 1);
long runningCount = 0;
for (int i = 0; i < CountsArrayLength; i++)
{
    runningCount += GetCountAtIndex(i);
    if (runningCount >= countAtPercentile)
        return HighestEquivalentValue(ValueFromIndex(i));
}
throw new ArgumentOutOfRangeException(...);

}

The nested loop computes GetCountAt(i, j)GetCountAtIndex(CountsArrayIndex(i, j)) anyway — the flat version eliminates the CountsArrayIndex call per iteration and improves cache locality by accessing memory sequentially.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions