title: Measuring code execution time
body: <p>I want to know how much time a procedure/function/order takes to finish, for testing purposes.</p>
  
  <p>This is what I did but my method is wrong 'cause if the difference of seconds is 0 can't return the elapsed milliseconds:</p>
  
  <p>Notice the sleep value is 500 ms so elapsed seconds is 0 then it can't return milliseconds.</p>
  
  <pre><code>    Dim Execution_Start As System.DateTime = System.DateTime.Now
      Threading.Thread.Sleep(500)
  
      Dim Execution_End As System.DateTime = System.DateTime.Now
      MsgBox(String.Format("H:{0} M:{1} S:{2} MS:{3}", _
      DateDiff(DateInterval.Hour, Execution_Start, Execution_End), _
      DateDiff(DateInterval.Minute, Execution_Start, Execution_End), _
      DateDiff(DateInterval.Second, Execution_Start, Execution_End), _
      DateDiff(DateInterval.Second, Execution_Start, Execution_End) * 60))
  </code></pre>
  
  <p>Can someone show me a better way to do this? Maybe with a <code>TimeSpan</code>?</p>
  
  <p>The solution:</p>
  
  <pre><code>Dim Execution_Start As New Stopwatch
  Execution_Start.Start()
  
  Threading.Thread.Sleep(500)
  
  MessageBox.Show("H:" &amp; Execution_Start.Elapsed.Hours &amp; vbNewLine &amp; _
         "M:" &amp; Execution_Start.Elapsed.Minutes &amp; vbNewLine &amp; _
         "S:" &amp; Execution_Start.Elapsed.Seconds &amp; vbNewLine &amp; _
         "MS:" &amp; Execution_Start.Elapsed.Milliseconds &amp; vbNewLine, _
         "Code execution time", MessageBoxButtons.OK, MessageBoxIcon.Information)
  </code></pre>