using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace DTS.Common.Utils { public class StopWatchQueue { private readonly Stopwatch _stopWatch; private readonly Queue _watchQueue; private readonly string _name; public StopWatchQueue(string name) { _stopWatch = new Stopwatch(); _watchQueue = new Queue(5000); _name = name; } private static double CalculateStdDev(IEnumerable values) { double ret = 0; var valuesArray = values as double[] ?? values.ToArray(); if (valuesArray.Length <= 1) return ret; //Compute the Average var avg = valuesArray.Average(); //Perform the Sum of (value-avg)^2 var sum = valuesArray.Sum(d => Math.Pow(d - avg, 2)); //Put it all together ret = Math.Sqrt(sum / (valuesArray.Length - 1)); return ret; } ~StopWatchQueue() { DumpData(); } public void DumpData() { if (_watchQueue.Count == 0) return; var qArray = new double[_watchQueue.Count]; for (var idx = 0; idx < qArray.Length; idx++) qArray[idx] = Convert.ToDouble(_watchQueue.Dequeue()) / Stopwatch.Frequency * 1000D; var qMax = qArray.Max(); var qMin = qArray.Min(); var qAvg = qArray.Average(); var qStd = CalculateStdDev(qArray); var fName = _name + DateTime.Now.ToFileTime() + ".csv"; using (var sw = new StreamWriter(fName, false)) { sw.WriteLine("The StopWatchQueue contains {0} entries", qArray.Length); sw.WriteLine("Max={0} Min={1} Average={2} StdDev={3}", qMax, qMin, qAvg, qStd); sw.WriteLine("All values in milli seconds"); for (var idx = 0; idx < qArray.Length; idx++) sw.WriteLine("{0},{1}", idx, qArray[idx]); } } public void Start() { _stopWatch.Start(); } public void Stop() { _watchQueue.Enqueue(_stopWatch.ElapsedTicks); _stopWatch.Reset(); } } }