Calculate Elapsed Time in .NET

I came across this while preparing an upcoming blog entry and felt the need to share. I was looking for a way to calculate the time of an operation. I searched over and over again only to find the following pattern:

DateTime startTime = DateTime.Now;
// do operation
DateTime endTime = DateTime.Now;
TimeSpan runTime = endTime - startTime;

Unfortunately, this pattern isn’t very accurate and rarely outputs anything other than zero on simple operations. I needed to output elapsed time for even these simple operation so I kept searching until finally I came across the System.Diagnostics.Stopwatch class. The code is more readable and (after a bit of testing) is capable of tracking the elapsed time of simple operations.

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// do operations
stopwatch.Stop();
TimeSpan runTime = stopwatch.Elapsed;
long runTimeMilliseconds = stopwatch.ElapsedMilliseconds;
long runTimeTicks = stopwatch.ElapsedTicks;

Hopefully, putting this out there will help people find this method much quicker than I did. And as my mother used to tell me: just because everyone else does it, it doesn’t make it right.

Advertisements

One thought on “Calculate Elapsed Time in .NET

  1. ed April 3, 2013 / 5:08 pm

    great tip, thanks!

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