Like everyone, I create little snippets of code to help me accomplish some programming task.
I found myself writing “stopwatch” code way too much. So, in my shared library that I use at home, I added this little static method that times how long code takes to run, and then returns a timespan:
/// Times how long <paramref name=”code”/>
/// takes to run.
/// <param name=”code”>An anonymous method or
/// <see cref=”Action”/> delegate that should
/// be run.</param>
/// <exception cref=”ArgumentNullException”>
/// When <paramref name=”code”/> is null.</exception>
public static TimeSpan TimeIt(Action code)
if (code == null)
throw new ArgumentNullException(“code”);
Stopwatch stopwatch = Stopwatch.StartNew();
// Run the code that was pass in.
I can now use that very easily anywhere I want to time something. The problem is, it returns a TimeSpan, and so more code is needed to output it somewhere. So, I created some extension methods for TimeSpan. These could be more well-thought out, but these will work for now:
public static class TimeSpanExtensions
public static void ToDebug(this TimeSpan timespan, String message)
Debug.WriteLine(timespan.ToString() + ” – “ + message);
public static void ToConsole(this TimeSpan timespan, String message)
Console.WriteLine(timespan.ToString() + ” – “ + message);
public static void ToMessageBox(this TimeSpan timespan, String message)
MessageBox.Show(timespan.ToString() + ” – “ + message);
This mean that in code, I can now do something like this:
for (int index = 0; index < 10000000; index++)
}).ToDebug(“Counted to 1 million.”);
And it creates output like this:
00:00:00.0455012 – Counted to 1 million.
As I’m learning and playing around more with .NET 4.0 and beyond, I really like and agree with the direction it’s going. The technology is becoming easier and easier to use. I like it!