.NET Tips and Tricks

Blog archive

Measure Performance with the Stopwatch Class

I like it when my code runs faster, but I don't want to work at it (if my application is running too slow, my time is usually better spent enhancing my data access rather than tweaking code). But if I do rewrite any code to make it run faster, I want to know that I made a difference. This has led me, after all these years, to the System.Diagnostics.Stopwatch class.

To use the Stopwatch class, just call its StartNew method, run your test, then call its Stop method. You can extract the elapsed time from the Stopwatch's ElapsedMilliseconds property then display it or write it to a log file. This example puts the result in a TextBox:

Dim  sw As System.Diagnostics.Stopwatch 
sw  = System.Diagnostics.Stopwatch.StartNew()
…something  to test…
sw.Stop()
Me.TextBox1.Text  = String.Format("Elapsed time: {0} ms", timer.ElapsedMilliseconds)
There are methods on the StopWatch class to reset the timer (so you can do another test) or restart the timer (so you can continue the current test). You can also get the elapsed time in Ticks or, for long running tests, as a TimeSpan object with hours, minutes, and (horrors!) days.

Posted by Peter Vogel on 03/21/2013


comments powered by Disqus

Featured

Subscribe on YouTube