Benchmark Method Execution Time in C#


Felis catusPhoto by pixolga

I often find myself debating the performance implications of various algorithms and alternate implementations. The only way to know for sure is to test the theory. Here is a quick and dirty way to benchmark the execution time of any method.

public static TimeSpan Time(Action action)
{
    Stopwatch stopwatch = Stopwatch.StartNew();
    action();
    stopwatch.Stop();
    return stopwatch.Elapsed;
}

An example usage:

TimeSpan time = Time(TestedMethod);
Console.WriteLine(String.Format("TestMethod executed in [{0}] ms",
                                                  time.TotalMilliseconds));

Leave a Reply

Notify me of followup comments via e-mail. You can also subscribe without commenting.