Timing Your C# Code with the Stopwatch Class

Introduction to System.Diagnostics.Stopwatch

There are a number of 3rd party tools that can help you profile your code and gauge things like the execution time, amount of memory consumed, number of loops, and other items useful in refactoring your code for optimal performance. There are even some tools natively available as part of Microsoft Visual Studio. These code profiling tools are designed to be used at development time to help optimize your code. As someone that has done a lot of C# programming as an asp.net developer, I find many of my solutions involve calling out to 3rd party service providers through web services or other types of integrations. There are often service level agreements with the 3rd parties that are hard to monitor if you don't take steps to ensure that there is timing information baked into your code around the integration point. The System.Diagnostics.Stopwatch class was designed for just this sort of use. It is a lightweight class used to track the amount of time elapsed between some starting and some ending point in time. Let's take a look at a couple of the properties and methods of the Stopwatch class:

  • Start() - start the stopwatch
  • Stop() - stop the stopwatch
  • IsRunning - indicator if the stopwatch is running or not
  • Elapsed - the TimeSpan measured by the current instance
  • ElapsedMilliseconds - the elapsed time measured by the current instance in milliseconds
  • ElapsedTicks - the elapsed time measured by the current instance in timer ticks

It is important to note that the System.Threading.Timer class is often mistaken to provide the type of functionality provided by the Stopwatch class. The Timer provides a mechanism for executing a method at a specified interval, which is completely different than tracking the amount of time elapsed between two points in time.

The following code snippet demonstrates how to wrap a timer around a block of code in order to track the amount of time elapsed since the start and ending execution of the particular block of code.

System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
timer.Start();

for( int loop = 0; loop < 100; loop++; )
{
System.Threading.Thread.Sleep(1000);
}
timer.Stop();
Console.WriteLine("Elapsed time is: {0}", timer.Elapsed);

I commonly wrap code like the example above around all of my service calls. I use an application setting to control whether the elapsed time is recorded. If it is enabled, then after the elapsed time is calculated it is written to a database or other logging location so that the overall performance of the service call can be monitored and tracked over time. This has proven invaluable to me as I have worked with various 3rd parties to improve the responsiveness of their provided services and ensure that the performance is trending at the target level.

Summary

We took an introductory look at the System.Diagnostic.Stopwatch class. We explored the value that using the stopwatch can provide in order to help monitor the performance of 3rd party services by tracking the time lapse in making calls to the 3rd party service.

About the Author:

Mark Strawmyer is a Senior Architect of .NET applications for large and mid-size organizations. Mark is a technology leader with Crowe Horwath LLP in Indianapolis, Indiana. He specializes in architecture, design and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C# again. You can reach Mark through http://markstrawmyer.com.

About the Author

Mark Strawmyer

Mark Strawmyer is a Senior Architect of .NET applications for large and mid-size organizations. He specializes in architecture, design and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C# for the fifth year in a row. You can reach Mark at mark.strawmyer@crowehorwath.com.

Related Articles

IT Offers

Comments

  • Jordan shoes mentioned Gene to go for the manufacturer, a margin of Nike

    Posted by TaddyGaffic on 04/24/2013 01:15pm

    In focus groups conducted at 80 community-based organizations around the country, Motivational Educational Entertainment of Philadelphia [url=http://markwarren.org.uk/property-waet.cfm]air max 90[/url] identified disturbing trends among youths ages 16 to 20. The "Just Say No" message of abstinence-only campaigns has been lost on this group of young people, who grew up during an era when the hip-hop sensibility of getting cash and clothes did not incorporate values of conscientious sexual behavior or social responsibility. Rappers who mingle [url=http://northernroofing.co.uk/roofins.cfm]nike free uk[/url] with glamorous-looking half-naked women rarely mention contraception while they're listing the number of compromising sexual situations they've been in lately. There are number of good brands in the market like Adidas, Nike, Reebok, Asics, Brooks, Puma etc. Most of these brands have shoes tailored for professional and amateur tennis players. New advanced technologies have made these shoes more player-friendly. After that, I eventually like to try to get down to the 150-160 range. I not entirely sure if that a healthy number for a gal my height or not, and I haven looked into it. But, I know that when I was 180 I still didn feel that [url=http://northernroofing.co.uk/roofins.cfm]nike free run uk[/url] fit, so I think an extra 20 or so will help with that.. Lotto sneakers selling price are generally liable along with using the form of sneakers you choose on. Your Lotto sneakers established fact because of their style along with good quality plus the create. That they create sneakers coming from all varieties much like the loafers,Puma II Shoes, new sandals, sneakers along with task tennis shoes or anything else

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Go Deeper

  • Off the rack CRM doesn't fit every business. Are you better off with a customized solution that addresses your unique business challenges? …
  • When the economy is stable, a company's IT organization may view Finance as just one of many internal customers competing for attention. But …
  • The number, complexity, and diversity of cyber threats are soaring. Businesses are increasingly concerned about the risks they face and 91% …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds