Wednesday, December 28, 2016

Boilerplate code to compare how long two operations take

This class allows you to wrap the stuff you want timed in a disposable using block. The timer is started when you enter the block and stops when the using clause is disposed.
void Main()
{
 double elapsed1 ;
 double elapsed2 ;
 var iterations = 1e7;
 using (var timedTask = new TimedTask("Method1"))
 {//Write your code here and measure its performance 
  for (var i = 0; i < iterations; i++)
  {
   Method1_DoStuff();
  }
  elapsed1 = timedTask.ElapsedMs();
 }

 
 using (var timedTask = new TimedTask("Method2"))
 {//Write your code here and measure its performance 
  for (var i = 0; i < iterations; i++)
  {
   Method2_DoStuff();
  }
  elapsed2 = timedTask.ElapsedMs();
 }
 
 if (elapsed1 < elapsed2)
  String.Format("method1 is {0:###,###.##}x faster than method 1", elapsed2/elapsed1, elapsed1, elapsed2).Dump();
 else
  String.Format("method2 is {0:###,###.##}x faster than method 2", elapsed1/elapsed2, elapsed1, elapsed2).Dump();

}

string Method1_DoStuff() {
 var x = "hello";
 x = x + " pretty";
 x = x + " world";
 return x;
}

private static string _field;
string Method2_DoStuff() {
 if (_field==null)
  _field = "hello pretty world";
 return _field;
}

class TimedTask : IDisposable
{
 string _taskName;
 Stopwatch sw;
 public TimedTask(string taskName)
 {
  _taskName = taskName;
  sw = new Stopwatch();
  sw.Start();
 }
 public double ElapsedMs()
 {
  return sw.Elapsed.TotalMilliseconds;
 }
 
 public void Dispose()
 {
  sw.Stop();
  string.Concat("completed ", _taskName, " in ", (sw.Elapsed.Ticks / 10000.0).ToString("###,##0.00 ms")).Dump();
 }


}


The result looks something like this:
completed Method1 in 559.24 ms
completed Method2 in 45.65 ms
method2 is 12.25x faster than method 2

download linqpad .linq file

No comments: