This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using Diagnostics.Performance; | |
namespace Diagnostics.Performance | |
{ | |
public static class Benchmarker | |
{ | |
private static void DisplayResults(string benchmarkName, | |
TimeSpan totalTime, | |
TimeSpan averageTime, | |
TimeSpan minTime, | |
TimeSpan maxTime) | |
{ | |
Console.WriteLine("---------------------------------"); | |
Console.WriteLine(benchmarkName); | |
Console.WriteLine("\tTotal time : " + totalTime.TotalMilliseconds + "ms"); | |
Console.WriteLine("\tAverage time: " + averageTime.TotalMilliseconds + "ms"); | |
Console.WriteLine("\tMin time : " + minTime.TotalMilliseconds + "ms"); | |
Console.WriteLine("\tMax time : " + maxTime.TotalMilliseconds + "ms"); | |
Console.WriteLine("---------------------------------"); | |
Console.WriteLine(); | |
} | |
public static void MeasureExecutionTime(string benchmarkName, | |
int noOfIterations, | |
Action action, | |
bool collectGcAfterEachIteration = true, | |
bool performWarmup = false) | |
{ | |
var minTime = TimeSpan.MaxValue; | |
var maxTime = TimeSpan.MinValue; | |
if (performWarmup) action(); | |
if (collectGcAfterEachIteration) CollectGC(); | |
var sw = Stopwatch.StartNew(); | |
for (int i = 0; i < noOfIterations; i++) | |
{ | |
sw.Restart(); | |
action(); | |
sw.Stop(); | |
if (collectGcAfterEachIteration) CollectGC(); | |
var thisIteration = sw.Elapsed; | |
if (thisIteration > maxTime) maxTime = thisIteration; | |
if (thisIteration < minTime) minTime = thisIteration; | |
} | |
var averageTime = new TimeSpan(sw.ElapsedTicks/noOfIterations); | |
var totalTime = new TimeSpan(sw.ElapsedTicks); | |
DisplayResults(benchmarkName, totalTime, averageTime, minTime, maxTime); | |
} | |
private static void CollectGC() | |
{ | |
GC.Collect(); | |
GC.WaitForPendingFinalizers(); | |
GC.Collect(); | |
} | |
} | |
} | |
namespace BenchmarkerDemo | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Benchmarker.MeasureExecutionTime("Benchmarker demo", 10000, () => | |
{ | |
var i = 1 + 10 + 100 / 42; | |
}); | |
Console.ReadKey(); | |
} | |
} | |
} |
No comments:
Post a Comment