System.Diagnostics.StopWatch Class

Imports System.Text
Module Module1
   Dim st1 As New Stopwatch ' Focus on this 
   Dim st2 As New Stopwatch '  and thus

   Sub Main()
      Test1(1000) ' 1000 iterations using StringBuilder
      Test2(1000) ' 1000 iterations using System.String
      Console.ReadLine()
   End Sub
   Private Sub Test1(ByVal i As Int32)
      st1.Start() ' ====================>Start counting
      Dim sb As New StringBuilder
      For x = 0 To i
         sb.Append("xyz")
      Next
      st1.Stop() ' ======================>Stop counting
      Console.WriteLine("Test1: {0} ticks {1}", st1.ElapsedTicks, sb.Length)
   End Sub
   Private Sub Test2(ByVal I As Int32)
      Dim sx As String
      Dim ss As String = ""
      st2.Start() ' ======================>Start counting
      sx = "xyz"
      For x = 0 To I
         ss += sx
      Next
      st2.Stop() ' ========================>Stop counting
      Console.WriteLine("Test2: {0} ticks {1}", st2.ElapsedTicks, ss.Length)
   End Sub
End Module

System.Diagnostic.StopWatch is good for comparing the amount of time it takes to do a routine and then compare with another. In the above case it takes 939 ticks to concatenate a string of 3 characters 1000 times.
Using System.String the same operation takes 19262 ticks; some 20 times more.

The point is: use System.Diagnostic.StopWatch for timing your own routines, not DateTime and/or TimeSpan which can't always be depended on to render accurate times. More about StringBuilder later.

10/11/2015
TheLonelyProgrammer.Net
Alone in a sea of non-programmers
Home