Skip to content

Instantly share code, notes, and snippets.

@esergueev
Created February 10, 2016 11:18
Show Gist options
  • Select an option

  • Save esergueev/d1fed3b5bee1002a3eaa to your computer and use it in GitHub Desktop.

Select an option

Save esergueev/d1fed3b5bee1002a3eaa to your computer and use it in GitHub Desktop.

Revisions

  1. Sergueev Eugene created this gist Feb 10, 2016.
    60 changes: 60 additions & 0 deletions PerformanceTester.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    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);
    }
    }
    2 changes: 2 additions & 0 deletions usage.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,2 @@
    var tester = new PerformanceTester(() => SomeMethod());
    tester.MeasureExecTimeWithMetrics(1000);