If you have ever wondered about how to properly measure execution
time in your application then this is the post for you. In this post I
will show you how to track time in your application with basic .NET,
then we will create a pretty abstraction to make sure you Don't Repeat Yourself (DRY).
Our focus will be around the Stopwatch class introduced in .NET 2.0. Stopwatch can be found under the System.Diagnostics namespace and is described by MSDN as follows:
[The Stopwatch class] provides a set of methods and properties that you can use to accurately measure elapsed time.
http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
Basics
// method #1
var stopwatch = new Stopwatch ();
stopwatch.Start ();
LongRunningProcess ();
stopwatch.Stop ();
Console.WriteLine ("Method #1 Total seconds: {0}", stopwatch.Elapsed.TotalSeconds);
There are four steps you need to take to use the Stopwatch class:
- Instantiate the Stopwatch class.
- Explicitly Start the stopwatch.
- Explicitly Stop the stopwatch.
- Output your results using Elapsed which is a TimeSpan.
Abstraction
So let's look at the final result and work our way backwards.
// method #2
using (Benchmark.Start("Method #2")) {
LongRunningProcess ();
}
Pretty sweet right? How am I achieving this? Well let me show you.
// Reuseable Stopwatch wrapper
public class Benchmark : IDisposable
{
Stopwatch _watch;
string _name;
public static Benchmark Start (string name)
{
return new Benchmark (name);
}
private Benchmark (string name)
{
_name = name;
_watch = new Stopwatch ();
_watch.Start ();
}
#region IDisposable implementation
// dispose stops stopwatch and prints time, could do anytying here
public void Dispose ()
{
_watch.Stop ();
Console.WriteLine ("{0} Total seconds: {1}"
, _name, _watch.Elapsed.TotalSeconds);
}
#endregion
}
We start the Stopwatch class as soon as we Start, and then we take advantage of IDisposable to Stop. When we do Stop,
we just output our result. You get completely reusable code and the
added benefit of just being able to wrap particular sections of
troublesome code. The nice thing about this abstraction is that it will
not interfere with your code paths. This is the output of both the first
and second method of using Stopwatch.
Conclusion
Stopwatch is an awesome class, use it when you are
wondering where your bottlenecks are. The abstraction I have included in
this post is easily adaptable to write out to anything that makes
sense: Database, Log files, EventLog, or Web Service. Give it a try and
let me know what you think, I'd love to hear your feelings.
P.S. I used Mono and Xamarin Studio to write this code, so don't be confused by the screenshot. :)
Comments
Post a Comment