Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Created March 16, 2021 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/556ee558db54dc6c390e39557133c771 to your computer and use it in GitHub Desktop.
Save guitarrapc/556ee558db54dc6c390e39557133c771 to your computer and use it in GitHub Desktop.
Calculate Latency distibutions
void Main()
{
var random = new Random();
var data = Enumerable.Range(0, 10000)
.Select(x => TimeSpan.FromMilliseconds(random.Next(1, 500)))
.OrderBy(x => x)
.ToArray();
Latencies(data).Dump();
}
private static readonly int[] percentiles = new int[] { 10, 25, 50, 75, 90, 95, 99 };
public LatencyDistribution[] Latencies(TimeSpan[] latencies)
{
var data = new double[percentiles.Length];
var length = latencies.Length;
// get percentile latency value
for (var i = 0; i < percentiles.Length; i++)
{
var percentile = percentiles[i];
var ip = (percentile / 100.0) * length;
var di = (int)ip;
// since we're dealing with 0th based ranks we need to
// check if ordinal is a whole number that lands on the percentile
// if so adjust accordingly
if (ip == (double)di)
di = di - 1;
if (di < 0)
{
di = 0;
}
data[i] = latencies[di].TotalMilliseconds;
}
var res = new LatencyDistribution[percentiles.Length];
for (var i = 0; i < percentiles.Length; i++)
{
if (data[i] > 0)
{
res[i] = new LatencyDistribution
{
Percentile = percentiles[i],
Latency = TimeSpan.FromMilliseconds(data[i]),
};
}
}
return res;
}
public struct LatencyDistribution
{
public int Percentile { get; set; }
public TimeSpan Latency { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment