From a13daa18db77b6ad2cd4b08b5bad5094aad84de3 Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Wed, 25 Jul 2018 11:59:25 -0400 Subject: [PATCH] feat: Profile method for performing an action a given number of times and printing results --- ICD.Common.Utils/Timers/IcdStopwatch.cs | 53 ++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/ICD.Common.Utils/Timers/IcdStopwatch.cs b/ICD.Common.Utils/Timers/IcdStopwatch.cs index a373ec1..3ece61d 100644 --- a/ICD.Common.Utils/Timers/IcdStopwatch.cs +++ b/ICD.Common.Utils/Timers/IcdStopwatch.cs @@ -130,6 +130,54 @@ namespace ICD.Common.Utils.Timers return output; } + /// + /// Executes the action the given number of iterations and prints timing information to the console. + /// + /// + /// + /// + public static void Profile(Action action, int iterations, string name) + { + if (action == null) + throw new ArgumentNullException("action"); + + if (iterations <= 0) + throw new ArgumentOutOfRangeException("iterations", "Iterations must be greater than 0"); + + name = string.Format("{0} ({1} Iterations)", name, iterations); + + long totalTime = 0; + List times = new List(iterations); + + for (int index = 0; index < iterations; index++) + { + IcdStopwatch stopwatch = StartNew(); + { + action(); + } + long duration = stopwatch.ElapsedMilliseconds; + stopwatch.Stop(); + + times.AddSorted(duration); + totalTime += duration; + } + + long averageTime = totalTime / iterations; + long medianTime = times[iterations / 2]; + long shortestTime = times[0]; + long longestTime = times[iterations - 1]; + + TableBuilder builder = new TableBuilder(name, "Duration (ms)"); + + builder.AddRow("Total", totalTime.ToString("n0")); + builder.AddRow("Average", averageTime.ToString("n0")); + builder.AddRow("Median", medianTime.ToString("n0")); + builder.AddRow("Shortest", shortestTime.ToString("n0")); + builder.AddRow("Longest", longestTime.ToString("n0")); + + IcdConsole.PrintLine(builder.ToString()); + } + /// /// Profiles getting each item from the enumerable. /// @@ -139,6 +187,9 @@ namespace ICD.Common.Utils.Timers /// public static IEnumerable Profile(IEnumerable enumerable, string name) { + if (enumerable == null) + throw new ArgumentNullException("enumerable"); + // TODO - Print a fancy table with a total duration for the sequence using (IEnumerator enumerator = enumerable.GetEnumerator()) @@ -218,7 +269,7 @@ namespace ICD.Common.Utils.Timers if (elapsed >= RED_MILLISECONDS) color = eConsoleColor.Red; - IcdConsole.Print(color, "{0}ms", elapsed); + IcdConsole.Print(color, "{0:n0}ms", elapsed); IcdConsole.PrintLine(" to execute {0}", name); }