Timing parts of your C# code with a using statement.

Timing (and tracing) specific parts of your code can often be necessary in order to trace what is going on in both a testing and production environment. For the sake of my own memory, and perhaps to the enjoyment of others,  I’ve decided to commit to the memory of the web a method for doing this that I find useful.

At one point I came upon a class in a colleague’s code called the LogicalOperationTimer. It is actually a lot more complicated and feature laden than what is shown here, and other variations exist on the web, but for the sake of principle this will suffice.

The idea is to create an IDisposable class that can wrap the code to be measured in the scope of a “using” statement. When the class is instantiated it starts a timer, and when the “using” scope ends, it automatically calls the Dispose() method of the class where you can the do the magic of saving the timer result to whatever media you prefer. In this case it’s just writing out the result to the console, but more practically it would be persisting it to disk in some form.

Here is the sample timer:

class LogicalOperationTimer : IDisposable
    private readonly Stopwatch _stopwatch = new Stopwatch();
    private readonly string _operationname;

    public LogicalOperationTimer(string operationname)
        _operationname = operationname;

    public void Dispose()
        Console.WriteLine("{0} : {1}ms", _operationname, _stopwatch.ElapsedMilliseconds);


More on the workings of the GC.SuppressFinalize can be found here. Now follows a very simple test of the above class:

    static void Main()
        using (new LogicalOperationTimer("Operation1"))
            // Measure this

        // Don't measure this


It’s the kind of code I like: short, clear and useful!

Posted in C#

One thought on “Timing parts of your C# code with a using statement.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s