C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
And: You can see that only two of the three 1-second loops were timed by the result.
SleepBut: There is usually no reason to benchmark everything. Use your own time wisely as well.
Benchmarks