Code sample: QuickTimer


As requested by Scott, here’s the code to QuickTimer.

public struct QuickTimer : IDisposable
    private readonly DateTime start;
    private readonly string label;

    public QuickTimer(string label)
        this.start = DateTime.UtcNow;
        this.label = label;

    void IDisposable.Dispose()
        DateTime end = DateTime.UtcNow;
        Console.WriteLine("QuickTimer: {0} ({1} ms)",
            (end - start).TotalMilliseconds);

Note that DateTime.UtcNow is not the most granular timer available on Windows–you probably want QueryPerformanceCounter for that. (The implementation we actually use in Windows Live Writer is based on the latter.)

Update: As mak points out in the comments, I should’ve used the Stopwatch class. I didn’t know about this class because all of my “real” coding is still done in .NET 1.1 on Visual Studio .NET 2003! Thanks mak!


using (new QuickTimer("Calculate pi to 10000 digits"))
    // expensive operation goes here

%d bloggers like this: