Stopwatch
This VB.NET type measures execution times. It is excellent for timing loads off of networks, measuring methods in benchmarks, and even measuring reaction times.
To create an instance of Stopwatch
, use the Stopwatch.StartNew
function. We can then call methods on the Stopwatch
instance to use it.
To start, we use Stopwatch.StartNew
. An alternative is to use the Stopwatch
constructor and then the Start function. Here we time a loop that takes about one second.
Elapsed.TotalMilliseconds
.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 Module2011.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.
Sleep()
does not sleep an exact number of milliseconds. You can see that only two of the three 1-second loops were timed by the result.The Stopwatch
type is extremely useful for learning more about .NET. With Stopwatch
, you can acquire an understanding of the relative times for certain statements to execute.
We used the StartNew
function on the Stopwatch
type, as well as the Start and Stop subroutines and the Elapsed property. We provided an overview of benchmarking and why it is important.