Skip to content

Instantly share code, notes, and snippets.

@DavidNepozitek
Created July 30, 2024 20:01
Show Gist options
  • Save DavidNepozitek/5db836f0b5b20c0da83a5b03044237e8 to your computer and use it in GitHub Desktop.
Save DavidNepozitek/5db836f0b5b20c0da83a5b03044237e8 to your computer and use it in GitHub Desktop.
HeadSamplingHistogramAlignedReservoir.cs
using System.Diagnostics;
using OpenTelemetry.Metrics;
namespace Exemplars;
public class HeadSamplingHistogramAlignedReservoir(IReadOnlyList<double> bounds) : FixedSizeExemplarReservoir(bounds.Count + 1)
{
private readonly bool[] _recordedWithSampledSpan = new bool[bounds.Count + 1];
public override void Offer(in ExemplarMeasurement<long> measurement)
{
Debug.Fail("HeadSamplingHistogramAlignedReservoir shouldn't be used with long values");
}
public override void Offer(in ExemplarMeasurement<double> measurement)
{
var bucketIndex = GetBucketIndex(measurement.Value);
if (_recordedWithSampledSpan[bucketIndex])
{
return;
}
UpdateExemplar(bucketIndex, in measurement);
if (Activity.Current?.Recorded is true)
{
_recordedWithSampledSpan[bucketIndex] = true;
}
}
protected override void OnCollected()
{
Array.Clear(_recordedWithSampledSpan);
}
private int GetBucketIndex(double value)
{
for (var i = 0; i < bounds.Count; i++)
{
if (value <= bounds[i])
{
return i;
}
}
return bounds.Count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment