C# Stopwatch Extension

Nice little extension to the stopwatch to allow for easy testing of the speed of a given method. FoundĀ here

public static class StopwatchExtensions
{
  public static long Time(this Stopwatch sw, Action action, int iterations)
  {
    sw.Reset();
    sw.Start(); 
    for (int i = 0; i < iterations; ++i)
    {
      action();
    }
    sw.Stop();
    return sw.ElapsedMilliseconds;
  }
}

To use it do this: –

var s = new Stopwatch();
Console.WriteLine(s.Time(() => DoStuff(), 1000));

 

 

Advertisement