Skip to content

Instantly share code, notes, and snippets.

@esergueev
Created February 10, 2016 11:18
Show Gist options
  • Save esergueev/d1fed3b5bee1002a3eaa to your computer and use it in GitHub Desktop.
Save esergueev/d1fed3b5bee1002a3eaa to your computer and use it in GitHub Desktop.
Micro Performance Testing Class
public class PerformanceTester
{
public TimeSpan TotalTime { get; private set; }
public TimeSpan AverageTime { get; private set; }
public TimeSpan MinTime { get; private set; }
public TimeSpan MaxTime { get; private set; }
public Action Action { get; set; }
public PerformanceTester(Action action)
{
Action = action;
MaxTime = TimeSpan.MinValue;
MinTime = TimeSpan.MaxValue;
}
public void MeasureExecTime()
{
var sw = Stopwatch.StartNew();
Action();
sw.Stop();
AverageTime = sw.Elapsed;
TotalTime = sw.Elapsed;
}
public void MeasureExecTime(int iterations)
{
Action(); // warm up
var sw = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
Action();
}
sw.Stop();
AverageTime = new TimeSpan(sw.Elapsed.Ticks/iterations);
TotalTime = sw.Elapsed;
}
public void MeasureExecTimeWithMetrics(int iterations)
{
TimeSpan total = new TimeSpan(0);
Action(); // warm up
for (int i = 0; i < iterations; i++)
{
var sw = Stopwatch.StartNew();
Action();
sw.Stop();
TimeSpan thisIteration = sw.Elapsed;
total += thisIteration;
if (thisIteration > MaxTime) MaxTime = thisIteration;
if (thisIteration < MinTime) MinTime = thisIteration;
}
TotalTime = total;
AverageTime = new TimeSpan(total.Ticks/iterations);
}
}
var tester = new PerformanceTester(() => SomeMethod());
tester.MeasureExecTimeWithMetrics(1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment