On GameSpot: Wii Fit tells 10-year-old she's fat

Determine elapsed time in VB.NET with Stopwatch

Tags: Microsoft development tools, Programming languages, Irina Medvinskaya, Microsoft Visual Basic.Net, StopWatch, Stopwatch object, Visual Basic Tips Newsletter

  • Save
  • Print
  • Digg This
  • 2

Takeaway: The Stopwatch object is useful for calculating the time that has elapsed between two time intervals in a VB.NET application. View an example to see how you can use this object in your development work.

A simple way to figure out how much time has passed since a particular moment in an application is to use the System.Diagnostics.Stopwatch object, which has been added in Visual Basic 2005. It's very useful for accurately timing loops and blocks of code; it's also helpful whenever you need to measure elapsed time with accuracy.

To use the Stopwatch object, you need to call its Start and Stop methods. When the Start method is called, the object begins counting the time. (The Reset method is useful if you need to clear the time count of the Stopwatch object.)

The example in Listing A uses the Stopwatch object. When the message box prompts you to click OK when you're ready to see the elapsed time is displayed, wait for a few moments and then click OK. You will see a message displaying the number of seconds that have passed since the stopwatch stpWatchInfo was started (stpWatchInfo.Start).

Notes about the example

I create the variable stpWatchInfo to use as a Stopwatch object. Then I use the object's Start method to have the Stopwatch start keeping track of the time that has passed. After clicking the OK button on the initial message box, I utilize the object's Elapsed property, specifying that I want to see the value in seconds by using stpWatchInfo.Elapsed.Seconds. The result is the message displaying the number of seconds that have elapsed since the Stopwatch object was started to the point when the user clicked the OK button.

Miss a tip?

Check out the Visual Basic archive, and catch up on the most recent editions of Irina Medvinskaya's column.

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!

  • Save
  • Print
  • Digg This
  • 2

Print/View all Posts Comments on this article

stopjojovalenton@...  | 03/16/07
Listing A is missingunderoverflow@...  | 03/16/07
Listing Asalinaspaul@...  | 03/16/07

What do you think?


advertisement
Click Here