The Stopwatch class provides a set of methods and properties that you can use to accurately measure elapsed time. Although its not a complete profiling solution it is very useful for things like quickly measuring code execution time.
A Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals.
Code Example
Public Class MainForm
Private m_PersonsList As New List(Of Person)
Private executionTimeWatch As New Stopwatch
Public Sub LogMethodExcecutionTime(ByVal methodName As String)
Me.executionTimeWatch.Stop()
Me.MethodExecutionTimesRichTextBox.AppendText(methodName & ": " & Me.executionTimeWatch.ElapsedMilliseconds.ToString & Environment.NewLine)
End Sub
Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.BuildPersonsList()
Me.DemoDataGridView.DataSource = m_PersonsList
Me.DemoDataGridView.Refresh()
End Sub
Private Sub BuildPersonsList()
' Begin timing this method.
Me.executionTimeWatch.Start()
For i As Integer = 1 To 100000
m_PersonsList.Add(New Person("FirstName" & i.ToString, "LastName" & i.ToString))
Next
Me.DemoDataGridView.Refresh()
' End timing method this method and log timing result.
Me.LogMethodExcecutionTime("BuildPersonsList")
End Sub
Private Sub SortButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SortButton.Click
' Begin timing this method.
Me.executionTimeWatch.Start()
m_PersonsList.Sort()
Me.DemoDataGridView.Refresh()
' End timing method this method and log timing result.
Me.LogMethodExcecutionTime("SortButton_Click")
End Sub
End Class
Click the link below to download free Visual Basic source code in a Visual Studio 2005 solution which demonstrates how to use the Stopwatch class to measure execution time for two methods.
StopWatch Class Example Source Code