VB.NET Stopwatch Example

The VB.NET programming language

How can you use the Stopwatch in your VB.NET program to measure execution times? The Stopwatch is excellent for timing loads off of networks, measuring methods in benchmarks, and even measuring reaction times.

This VB tutorial provides examples for the Stopwatch type from System.Diagnostics.

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. Finally, we start timing and run the loop a third time. We call Stop and then display the time elapsed by accessing Elapsed.TotalMilliseconds. This represents the time in total number of milliseconds.

Program that uses Stopwatch [VB.NET]

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
Question and answer

Results. 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. In any case, you can see that only two of the three 1-second loops were timed by the result.

Sleep Method

Usefulness

Programming tip

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. There is usually no reason to benchmark absolutely everything, however. Use your own time wisely as well.

Summary

We looked at how you can use 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.

VB.NET Tutorials
.NET