# Recipe 7.6. Calculating Elapsed Time with the Stopwatch

#### Problem

You want to measure elapsed time accurate to the nearest millisecond.

#### Solution

Sample code folder: Chapter 07\ElapsedStopwatch

Use the Stopwatch object, which is designed to measure elapsed milliseconds accurately.

#### Discussion

The new System.Diagnostics.Stopwatch object introduced with Visual Basic 2005 provides better-resolution timing than using system ticks. The ElapsedMilliseconds property accurately returns elapsed time to the nearest millisecond, as demonstrated in Recipe 7.4. This is ideal for timing blocks and loops of code to compare the efficiency of various algorithms or for other high-resolution timing tasks. The following code times how long the user takes to click an OK button when prompted:

` Dim testWatch As New System.Diagnostics.Stopwatch Dim results As String ' ----- Start counting. testWatch.Start() MsgBox("Press OK to see elapsed seconds") ' ----- Stop and record. results = String.Format( _    "testWatch.Elapsed.Seconds: {0}{3}" & _    "testWatch.Elapsed.TotalSeconds: {1}{3}" & _    "testWatch.ElapsedMilliseconds / 1000: {2}", _    testWatch.Elapsed.Seconds, _    testWatch.Elapsed.TotalSeconds, _    testWatch.ElapsedMilliseconds / 1000, vbNewLine) MsgBox(results) `

The Elapsed property returns a TimeSpan object, which provides properties useful for extracting time durations. In this example the whole number of seconds is returned by the TimeSpan's Elapsed.Seconds property, and a more exact decimal number of seconds is returned by its Elapsed.TotalSeconds property. Figure 7-6 displays the results.

##### Figure 7-6. Using the Stopwatch object to accurately measure elapsed time

When using a Stopwatch, be sure to call its Start() method before attempting to access elapsed time from it. If Start() is not called first, elapsed time is always returned as zero.

You can accumulate elapsed time in pieces by calling the Start() and Stop() methods repeatedly. The elapsed time freezes when Stop() is called; the counting resumes when Start() is called. To clear the Stopwatch's count at any time, call the Reset() method. These methods simulate the buttons on a real stopwatch, but do so much faster and more accurately than punching buttons by hand!

Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400