Saturday, April 12, 2008

Using System.Diagnostics.StopWatch

In the old days if wanted to do a quick performance test you could write a test and track the start and end time and see what the difference was between them. Now there is a StopWatch class that can do this for you!
My friend Jake and I were talking about doing quick performance tests on exception handling. We can definitely use this handy class to help out with that.
using System.Diagnostics;

[Test]
public void StringBuilderTest()
{
    Stopwatch watch = new Stopwatch();
    watch.Start();

    StringBuilder sb = new StringBuilder();
    int iterations = 10000000; // 10 million
    for (int i = 0; i < iterations; i++)
    {
        sb.Append(i);
    }

    watch.Stop();
    Console.Write("Elapsed Time: " + watch.Elapsed);
}
More Info: MSDN: Stopwatch Class