VB.NET Stopwatch Example

Use the Stopwatch type from System.Diagnostics to time a piece of code. Call StartNew and Stop.

Stopwatch. This measures execution times. It is excellent for timing loads off of networks, measuring methods in benchmarks, and even measuring reaction times. We test this type in this example program.

Example. To create an instance of Stopwatch, use the Stopwatch.StartNew function. An alternative is to use the Stopwatch constructor and then the Start function. In this example, we time a loop that takes about one second.

Then: We stop timing and run the same loop again. Next we start timing and run the loop a third time.

And: We call Stop and then display the time elapsed by accessing Elapsed.TotalMilliseconds.

Tip: This represents the time in total number of milliseconds. It contains a fractional part.

VB.NET program that uses Stopwatch Module Module1 Sub Main() ' Create new Stopwatch instance. Dim watch As Stopwatch = Stopwatch.StartNew() ' Measure. For i As Integer = 0 To 1000 - 1 Threading.Thread.Sleep(1) Next ' Stop measuring. watch.Stop() ' This isn't measured. For i As Integer = 0 To 1000 - 1 Threading.Thread.Sleep(1) Next ' Begin measuring again. watch.Start() ' Measure. For i As Integer = 0 To 1000 - 1 Threading.Thread.Sleep(1) Next ' Stop measuring again (not always needed). watch.Stop() Console.WriteLine(watch.Elapsed.TotalMilliseconds) End Sub End Module Output 2011.6659

Why is the total time required to execute two loops of 1000 1-millisecond Sleep calls more than 2000 milliseconds? The Sleep method has some margin of error. It does not sleep an exact number of milliseconds.

And: You can see that only two of the three 1-second loops were timed by the result.


Discussion. The Stopwatch type is extremely useful for learning more about VB.NET and the .NET Framework. With Stopwatch, you can acquire an understanding of the relative times for certain statements to executed.

This can yield significant performance improvements as you build your knowledge. I recommend doing some level of benchmarking as you develop programs, at least when you are new to the Framework.

But: There is usually no reason to benchmark everything. Use your own time wisely as well.


Summary. We used the StartNew function on the Stopwatch type, as well as the Start and Stop subroutines and the Elapsed property. Finally, we provided an overview of benchmarking in the VB.NET language and why it is important.DateTime
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to