Timing a Method in C#

Here’s a very quick way to check the performance of a block of code. I’m wrapping a System.Diagnostics.Stopwatch class and sending all timings directly to Debug.WriteLine(). Please be aware that this is a very simplistic approach, and does not guarantee accurate timings.

If you need a more professional approach you may want to check out these tools:
ANTS Profiler
dotTrace Profiler
EQATEC Profiler (Free)

using System;
using System.Diagnostics;

public class Profiler : IDisposable
    private Stopwatch _stopWatch;

    public Profiler() : this("Untitled")
    { }

    public Profiler(string title)
        _stopWatch = new Stopwatch();

    public void Print(string comment)
        Debug.WriteLine("  {0,-30} {1,10} ms", Crop(comment, 30), _stopWatch.ElapsedMilliseconds);

    public void Dispose()
        Debug.WriteLine("{0,-30}   {1,10} ms", "Total", _stopWatch.ElapsedMilliseconds);
        _stopWatch = null;

    private string Crop(string input, int length)
        if (input.Length > length)
            return input.Substring(0, length - 3) + "...";
            return input;

To measure how quickly a block of code runs, wrap the code in a using statement that creates a new Profiler instance. The Stopwatch begins timing as soon as the Profiler is initialized, and stops when execution moves outside the using block. The current elapsed time can be output by adding a call to Profiler.Print().

private void CalculateTax(decimal amount)
    using (var profiler = new Profiler("CalculateTax"))
        // Initialize something
        // ...

        // Output intermediate progress
        profiler.Print("Starting tax calculation");

        // Do something
        // ...

A typical output from the example above would appear in the Output Window as this:

  Starting tax calculation                3 ms
Total                                   132 ms
This entry was posted in Tips and Tricks and tagged , . Bookmark the permalink.

2 Responses to Timing a Method in C#

  1. CrackG says:

    Thanks Code Overlord!! That was a massive help..you rock!

  2. Pingback: Grippers.co.uk

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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s