public MetricTelemetry GetValueAndReset() { long curValue = Interlocked.Exchange(ref this.compositeValue, 0); int curMinValue = this.minValue; int curMaxValue = this.maxValue; minValue = Int32.MaxValue; maxValue = Int32.MinValue; var count = (int)(curValue & ((1 << 24) - 1)); double value = curValue >> 24; var metric = this.GetInitializedMetricTelemetry(); if (count != 0) { metric.Value = value / count; metric.Count = count; if (this.shouldCalculateMinMax) { metric.Min = curMinValue; metric.Max = curMaxValue; } else if (this.shouldCalculatePercentiles) { List <double> curListValues = Interlocked.Exchange(ref this.listValues, new List <double>()); PercentileAggregations percentiles = CalculatePercentiles(curListValues); metric.Properties.Add(Constants.P50Name, percentiles.P50.ToString(CultureInfo.InvariantCulture)); metric.Properties.Add(Constants.P75Name, percentiles.P75.ToString(CultureInfo.InvariantCulture)); metric.Properties.Add(Constants.P90Name, percentiles.P90.ToString(CultureInfo.InvariantCulture)); metric.Properties.Add(Constants.P95Name, percentiles.P95.ToString(CultureInfo.InvariantCulture)); metric.Properties.Add(Constants.P99Name, percentiles.P99.ToString(CultureInfo.InvariantCulture)); } } else { metric.Value = 0; metric.Count = 0; } return(metric); }
private PercentileAggregations CalculatePercentiles(List <double> values) { PercentileAggregations percentiles = new PercentileAggregations(); values.OrderBy(i => i); int percentile50Index = GetPercentileNearestIndex(values.Count, 50); int percentile75Index = GetPercentileNearestIndex(values.Count, 75); int percentile90Index = GetPercentileNearestIndex(values.Count, 90); int percentile95Index = GetPercentileNearestIndex(values.Count, 95); int percentile99Index = GetPercentileNearestIndex(values.Count, 99); int listValueIndex = 0; foreach (double value in values) { if (listValueIndex == percentile50Index) { percentiles.P50 = value; } else if (listValueIndex == percentile75Index) { percentiles.P75 = value; } else if (listValueIndex == percentile90Index) { percentiles.P90 = value; } else if (listValueIndex == percentile95Index) { percentiles.P95 = value; } else if (listValueIndex == percentile99Index) { percentiles.P99 = value; } listValueIndex++; } return(percentiles); }