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();

for( int loop = 0; loop < 100; loop++; )
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.


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


  • Cheap Oakley Half Jacket sale online

    Posted by yeqdapedl on 07/09/2013 02:54pm

    Oakleys Fake ,Oakley provides cover prescription lenses, sunglasses, and they intend to this summer making sure that individuals than the fantastic visual is visible. USA Cycling legend Lance Armstrong Lance Armstrong, LIVESTRONG founder, we previously reported a big joint planning, joint project with NIKE. Regardless if you are inside a family, skating within the beach, or just nursing your hangover, cheap Oakley sunglasses to your perfect accessories. Fake Oakley Oil Rig ,Oakley is really a trend, and provides real-world imitate two glasses of sunglasses models, this is a well-known optical company Bausch & Lomb Bausch & Lomb brand. If you are what sort of person, and a couple of sunglasses, it is in your case. These sunglasses can be extremely built to meet the requirements off personal taste. The sunglasses may be split up into many different kinds, points according to the functional use. Ordinary sunglasses, decorative sunglasses, driver sunglasses and so on. Sunglasses, cleaning fluid is incredibly particular, want to know would it be is just not correct make use of paper or fingernails, because it's easily scratched sunglasses products. Cheap Oakley Sunglasses ,If you've got the OAKLEY shades meters framework to adopt selling point of them within the beach or skiing, to strengthen all HLS is really a real ice section, you will be the main difference of any two small brown eyes, browse them. Eliminate from the glare of light, also lessen the power on the eyes, Oakley, actually, is especially thought to be the ultimate degree of functioning, the employment of polarized lenses. Cheap ray ban ,Oakley sunglasses are great males and females, brand sunglasses, Oakley, the sunglasses are stylish and useful, many people enjoy it. I always realize that we are going to succeed. This belief originates from you believe the ongoing cause, making every effort to own ultimate perfection. longchamp pas cher ,Polarized sunglasses, export to your account as well as the ability to take care of the very best security, so that you will take notice of the clear, you may also find the the best option for dynamic lifestyle completely one. Expensive to secure a good salary of excellent quality and Oakley sunglasses women quite a while to joy, as well as get Oakley sunglasses single for each and every scene. So that you can fulfill the different needs of consumers, either now or perhaps the future, Oakley won't stop the pace of progress.

  • Which headphones should i corrupt

    Posted by motherdhmm on 06/04/2013 02:29pm

    [url=http://blog.cheapbeatsbydre.co.nz/]beats by dre nz[/url] A fate of simulate, Barbarity Beats Studio, online blow the whistle on buy like basis penalty to attract more people to bribe their products, their prices are deeply cheap. But you obligated to not exclusive determine to procure because they are cheap, in addition to price, should learn more fro Bogeyman¡¯s quality. When you¡¯re likely to pay off a Monstrosity Beats Stud, online, you ought to go to a handful online department store to be aware of and deviate from, and for all make a creme de la creme is recommended. [url=http://www.headphonescheaponlineaustralia.com/]beats by dre[/url] Monster headphones in Australia more and more in fashion, more people drink thebeats close to Dre, a feature that was seen via some lawbreakers business opportunities, so, followed beside distribution of charlatan and shoddy products and markets, to manyconsumers in trouble, to invest a lot of in money to secure is not authentic beats during dre beats by Dre. Again, if you¡¯re reading this, then you are lucky, the contemplating that the next wish be to mention, purchase factual beats nigh dre should be well-known that the treaty of these later in the acquiring of a monster headphones you can purchase veritable the. [url=http://www.headphonescheaponlineaustralia.com/]monster beats Australia[/url] Fitting for Missing link headphones australia, the voice is eternally the most important. When it is indicated to each time we using beats by dre australia cheap headphones. We hope that at the time of you are enjoying the music, you would not be disturbed nigh the wind of the cable. Miscreation the beats nigh dr dre casual headphone adopted the new stretched out cabel which can bar the radio from winding, with the design of long-wearing plugs, you could enjoy your fair-haired boy music without the arid the winding line cause to you.

  • Alvorlige salg høykvalitets hodetelefoner av Dr. Dre

    Posted by mantouhmmm on 06/04/2013 08:14am

    [url=http://www.beatsdrenorge.webgarden.com/]Monster Beats norge[/url] Lav overflod er fortsatt Studio fokus - forutsatt tiltalende akseptabelt i lav frekvens. Ikke som Tour, er Flat lav overflod tykkere og enklere, ingen overdriver bottomward men bare affære behovene til musikk som Hip-Hop. Topp overflod er en av de aspektene som vi aksepterer kritisert on Tour - det er for aciculate og ikke omgjengelige i det hele tatt. Mens Flat betaler ekstra absorpsjon til antitese og lav overflod - litt "overkompensasjon" på toppen frekvens, motvektstrucker og litt defekt av detaljer. Derfor er som en dyktig Flat artikulasjon sentrert i gjennomsnittlig overflod og lav overflod som ikke er faktisk akseptabelt for som liker flammer akutt stemme. På slutten av artikkelen, anerkjennelse jeg hotsalesmart.com til deg, Monster beats by dr. dre flat alene er $ 169 til $ 219 for chargeless forsendelsen hjem. [url=http://www.beatsdrenorge.webgarden.com/]beats by dre norge[/url] Stil og farge. elegant og stilig hode beskyttelse, dette Bests dre etter Bests ved hjelp av dre Expedition har en enestående overdreven bakgrunn forstyrrelse demping i tillegg til et resultat av den betydelige ytterste støy etterspørsel nivåer som hodetelefoner er perfekt for støy montører, utøvere i tillegg til DJ-er. Produktiv Tesla transdusere på Bests ved hjelp av dre Expedition forsikre en slags vidunderlig pent balansert i tillegg til analytisk støy. Den utover vanlig høyere nivå av ferdigheter er en fordel beregnet for sluttbrukere med høye desibel forhold som støy montører så snart som evnen til å høre PA-programmer eller kanskje utøvere. [url=http://www.beatsbydrestudio.moonfruit.com/]beats by dre studio[/url] Beats nær Dre Tour ControlTalk inear Hodetelefoner Purple98.00 billige beats Purple er screechy kvalitet, og ingen verdt shipping.Jul 25, rød-farget hodetelefoner grunn riktig er for sleazy kostnaden allot grade bare én kvalitet. Hugeness Dr Dre Solo HD rød-farget hodetelefonene er monster beats nær dre solo hd hodetelefoner sted salg, slår alle monster solo hd sted øret hodetelefoner markedet hugeness slår av Dr Dre solo hd hugeness slår nær dre solo hd stor Definition Sound, behagelig passform , Light allot Compact handel hver enkelt Lifestyle, ControlTalk.ColorWare gir tilpasse tjenestene sted Beats Solo HD. monster beats tour nær Dre. Beats Solo HD-hodetelefoner er lilje innenfor av dalen ny kompakt utgave av Beats nærheten av Dr. Dre.

  • Hvad er forskellen mellem øret og øret

    Posted by wanzixiao on 06/04/2013 06:25am

    [url=http://www.beatsbydrdredanmark.webstarts.com/]beats by dre danmark[/url] Jeg har efterhånden været indehaver af dette pragteksemplar i knap ét og jeg nyder hvert et øjeblik i selskab med mine Beats. Der er ingen tvivl om, at de har taget verden med storm og de er kommet for at blive. Det kan tage lang tid at finde det rette headset, men med disse Beats by Dr. Dre Studio er jeg tydeligvis ikke gået galt i byen på noget tidspunkt. Hverken i forhold til min stationær, [url=http://www.kbhretelefonerbillig.webstarts.com/]Køb høretelefoner billig[/url] Hvis du interesserer lyden, hvordan man kan lytte til din musik, så vil du elske deBeats by Dr. Dre solo højtydende hovedtelefoner. Uanset om du er fagfolk eller entusiaster, de er den perfekte høj kvalitet at lytte til dig igen, hvis du interesserer lyd, hvordan du kan lytte til din musik på farten, så vil du elske beat af Dr. Dre Solo high-performance hovedtelefoner. Uanset om du er fagfolk eller entusiaster, de er perfekte, høj kvalitet lytter til dig på vejen. [url=http://www.beatsbydrdredanmark.moonfruit.com/]beats by dre danmark[/url] Projektet kan opnås på en måde at bruge god til handling og magt lav overflod, og værdiskabende tilbehør. Den faktiske headset komfort element er virkelig stor. Du vil finde disse slag Dre taktslag buy berømtheder certificering af DRE pro at slå Dre studio hovedtelefoner i øret. BIII komme med en rengøringsklud til at sikre, at de er på udkig efter. For nylig fandt jeg en fælles ven kørte vej sat på afDr. Dre Studio hovedtelefoner, derfor vil jeg opfordre til at spørge hende, hvordan de ser ud.

  • Precio de oro series GHD, comentarios ghd tienda online

    Posted by hanmeihm on 05/30/2013 04:48pm

    [url=http://www.planchasghdbaratasonline.com/ghd-Peacock-Coleccion/]ghd Peacock[/url] usted puede hacer un ghd en Sephora sobre como $ 200but asegurarse de que son el estado de la t¦cnica. se alinean r¢pidamente, lo dejan suave y hacen-brillante. aydales increble, amo a todos. ] ghds son, evidentemente, alisadores de pelo maravillosas. su propio trabajo de enderezamiento es cool. tienen los ltimos modelos de y su pelo se mantenga recta durante m¢s tiempo. pero remember1. vas a enderezar su cabello todos los das 2. Tiene suficiente dinero para pagar un now3 ghd derecha. Qu¦ problema si un ser un poco menos caro, para casi el mismo resultsif usted contest s a dos de estas preguntas, te recomiendo un poco de negocios leadinger plancha de pelo. noches pelo satisfechos) [url=http://www.planchasespanaghdtop.net/]ghd espa?a[/url] La primera straightner ghd era b¢sicamente aos antes de la competitividad ltimos dos mil. Planchas para el pelo durante ese tiempo el peso placas de aluminio muy ligeros y un montn de sauna elegido como medida para encontrar la mejor apariencia. La clave en la parte trasera de la m¢s alta eficacia de su ghd era b¢sicamente la derecha abajo a varios elementos principales. [url=http://www.planchaspeloghdes.qsite.dk/]planchas ghd baratas[/url] Un nmero de consumidores es elementos altamente alrgicas en tinte de cabello y el proceso podra ser peligroso Hacer en la consulta de su mdico y no compro nada por su cuenta, ghd outlet , pero hay que recordar que tales mercancas normales utilizando para cuidado del cabello por s mismo no es suficiente.

  • 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

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

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date