Determine elapsed time in VB.NET with Stopwatch
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!
Print/View all Posts Comments on this article
SponsoredWhite Papers, Webcasts, and Downloads
- An Introduction to Windows Server 2008 Server Manager Global Knowledge
- What You Need To Know About Server 2008 Core Edition Global Knowledge
- BitLocker: Is It Really Secure? Global Knowledge
Article Categories
- Security
- Security Solutions, IT Locksmith
- Networking and Communications
- E-mail Administration NetNote, Cisco Routers and Switches
- CIO and IT Management
- Project Management, CIO Issues, Strategies that Scale
- Desktops, Laptops & OS
- Windows 2000 Professional, Microsoft Word, Microsoft Excel, Microsoft Access, Windows XP,
- Data Management
- Oracle, SQL Server
- Servers
- Windows NT, Linux NetNote, Windows Server 2003
- Career Development
- Geek Trivia
- Software/Web Development
- Web Development Zone, Visual Basic, .NET

