Recipe 7.4. Timing Application Activities


Problem

You want to time application events with greater accuracy than is provided by the Date type's Ticks property.

Solution

Sample code folder: Chapter 07\ Stopwatch

Use the System.Diagnostics.Stopwatch object to accurately determine elapsed time to the nearest millisecond.

Discussion

The new System.Diagnostics.Stopwatch object is easy and intuitive to use. Just like a real stopwatch, you start it when you want and measure elapsed time as needed. The Start() method starts the timing, and the ElapsedMilliseconds property returns the number of elapsed milliseconds. Similarly, there are Stop() and Reset() methods to stop and reset the stopwatch, and these methods behave as you'd expect.

The following code demonstrates how to create an instance of the Stopwatch object and how to measure elapsed time with it. But it also points out an advantage of using this object for fine-grained timing measurements rather than using Ticks. The Do…Loop block of code runs for one second, tallying the number of times the value returned by the ElapsedMilliseconds property changes to a new value:

 Dim lastMillis As Long Dim numMillis As Long Dim testWatch As New System.Diagnostics.Stopwatch Dim endTime As Date Dim results As String ' ----- Start the timer. endTime = Now.AddSeconds(1) testWatch.Start() Do    ' ----- Keep track of each change of the stopwatch.    If (testWatch.ElapsedMilliseconds <> lastMillis) Then       numMillis += 1       lastMillis = testWatch.ElapsedMilliseconds    End If Loop Until (Now > endTime) ' ----- Display the results. results = "Elapsed milliseconds: " & _    testWatch.ElapsedMilliseconds.ToString & vbNewLine & _    "Number of updates per second: " & numMillis.ToString MsgBox(results) 

As shown in Figure 7-4, the property returns a new number of elapsed milliseconds slightly over 1,000 times during the second, a result to be expected when the loop timing is based on the system clock. Hence, the Stopwatch is accurate to the nearest millisecond.

Figure 7-4. The Stopwatch object accurately maintains a timing resolution of one millisecond


See Also

Compare the results of this recipe with those of Recipe 7.3, which provides a lower level of accuracy.




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

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net