IDisposable StopWatch to Benchmark code blocks (via Lambda or Delegate) in C#

Sometimes you need to time code execution for use *inside* your application. the StopWatch class was designed just for this purpose, but you end up with some pretty ugly code that looks like this:

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// Do something.
for (int i = 0; i < 1000; i++) { Thread.Sleep(1); }
// Stop timing.
stopwatch.Stop();
// Write result.
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);

This gets really messy, especially if the code is already pretty complicated. But with very little effort you can make the .Net StopWatch just as beautiful as the Benchmark class in Ruby.

public class DisposableStopwatch: IDisposable {
  private readonly Stopwatch sw;
  private readonly Action f;

  public DisposableStopwatch(Action f) {
    this.f = f;
    sw = Stopwatch.StartNew();
  }

  public void Dispose() {
    sw.Stop();
    f(sw.Elapsed);
  }

}

To use the new stopwatch:

using (new DisposableStopwatch(t => Console.WriteLine("{0} elapsed", t)) {
  // do stuff that I want to measure
}

This is the best solution I’ve ever seen for this problem! No extension (so that it can be used on many classes) and very clean and very simple!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.