Skip to content

Instantly share code, notes, and snippets.

@cybermaxs
Created June 4, 2015 08:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cybermaxs/ce252a7516203addb1a4 to your computer and use it in GitHub Desktop.
Save cybermaxs/ce252a7516203addb1a4 to your computer and use it in GitHub Desktop.
Extension methods for performance statistics (avg, median, centiles)
using System;
using System.Linq;
namespace MyNamespace
{
public static class PerfStatsExtensions
{
public static double? Avg(this double[] values)
{
if (values == null) return null;
double total = 0D;
long nb = 0L;
foreach (double val in values)
{
total += val;
nb += 1L;
}
if (nb > 0L)
{
return total / (double)nb;
}
return 0D;
}
public static double? Percentile(this double[] values, double percentile)
{
if (values == null) return null;
Array.Sort(values);
int N = values.Length;
double n = (N - 1) * percentile + 1;
if (n == 1d) return values[0];
else if (n == N) return values[N - 1];
else
{
int k = (int)n;
double d = n - k;
return values[k - 1] + d * (values[k] - values[k - 1]);
}
}
public static long LessThan(this double[] values, double value)
{
if (values == null) return 0L;
return values.Where(v => v < value).LongCount();
}
public static double PercentLessThan(this double[] values, double value)
{
if (values == null) return 0D;
return 100D * values.Where(v => v <= value).LongCount()/values.Count();
}
//shortcuts
public static double? _50th(this double[] values, double percentile)
{
return values.Percentile(0.5D);
}
public static double? _70th(this double[] values, double percentile)
{
return values.Percentile(0.7D);
}
public static double? _90th(this double[] values, double percentile)
{
return values.Percentile(0.9D);
}
public static double? _95th(this double[] values, double percentile)
{
return values.Percentile(0.95D);
}
public static double? _99th(this double[] values, double percentile)
{
return values.Percentile(0.99D);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment