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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: