Click here to Skip to main content
12,826,440 members (26,167 online)
Click here to Skip to main content
Add your own
alternative version


40 bookmarked
Posted 27 Nov 2002

Stopwatch - a High-Resolution code timer class

, 27 Nov 2002
Rate this:
Please Sign up or sign in to vote.
A high-resolution code timer for VB.NET using Kernel32 functions


Creating an application requires precisely measuring how long specific operations take to complete. You may be searching for performance bottlenecks prior to shipping, measuring to ensure that changes do not unexpectedly degrade performance, or (in my case), testing alternative architectural approaches. You can use a real stopwatch and measure your application's response time, but fumbling and other miscues will render about a 1/4 second (0.25) resolution, at best. The Tick count available in VB is more accurate and fumble-proof, and it has a resolution of about 10ms (0.01).

The Windows Kernel includes a much finer-grained tick counter, which it exposes in an API call named QueryPerformanceCounter. This timer boasts near microsecond (0.000001) resolution and is easily callable from VB. The Stopwatch class wraps this call, masking all the sordid details.


Stopwatch merely implements the code described in Microsoft Knowledge Base article 306978 (10/02) in a easily used class. I can't claim any originality - the technical details are by Microsoft, and the "stopwatch" class idea is from an old C++ article I read in 1993 or so (and implemented back then using mmsystem.dll in Windows 3.1; yikes!).

Using the code

There are two ways to use Stopwatch: create a Stopwatch instance and tell it to ReportToConsole when the code being measured is done; or reuse a single Stopwatch instance again and again, saving off elapsed time values each time.

Here's a very simple way to display how long a process takes on the console:

Dim swatch as New Stopwatch("My process")
'Perform my process (presumably a loop or one or more method calls)

'Output: "My process (0.332131039000767 seconds)"

You can use the same Stopwatch instance repeatedly:

Dim firstResult, secondResult as Double
Dim swatch as New Stopwatch()
'...perform process...
firstResult = swatch.ElapsedTime() ' Note: ElapsedTime does 
                                   ' not stop the clock
'...more process work...
secondResult = swatch.ElapsedTime()
    "First took {0} seconds; First and Second took {1} seconds.", _
    firstResult, secondResult)
'...a third bunch of work...
MsgBox("The third thing took " & CStr(swatch.ElapsedTime()) & " seconds.")

'Output: "First took 0.0131530683368976 seconds; 
'First and Second took 8.8372527793337 seconds."

Points of Interest

This code also manages to demonstrate how to call the Windows API and how to define a custom exception class. Microsoft Knowledge Base article 172338 describes how to use QueryPerformanceCounter in VB 6 and other environments, and it contributed the idea of calculating the API call overhead so that it could be subtracted from the result.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Alastair Dallas
Web Developer
United States United States
Alastair Dallas is a programmer, systems architect, and information designer with over 20 years experience at companies including Ashton-Tate, Lotus, Netscape, Documentum, and a wide variety of startups. Languages include C#, C, C++, Java, JavaScript, Perl, Python, and VB (in alphabetical order) as well as DHTML, XML, and related technologies. He has written 3 books, 2 on computer topics, and is President of Infospect Press.

You may also be interested in...

Comments and Discussions

QuestionIs there a way to get the stopwatch instant to callback events? Pin
seanclancy15-Oct-08 10:01
memberseanclancy15-Oct-08 10:01 
QuestionAccurate???? For real?? Pin
becker66620-May-07 15:50
memberbecker66620-May-07 15:50 
I tried similar code and different incarnations and at the beginning it seems to work but putting into a loop the accuracy goes down the toilet
as soon as the program gets interrupted by the OS (every 10-15msec)
I wa trying to generate a 10400 baud(~ 96uSec timer) at a pin on the parallel port got all pump up with the perf-API's and after starting sampling I got let down.

I'm not even sure if it is possible to generate an accurate constant timer of that lower precision that does not flake out every period of time
any suggestions??? I'm headng to an old DOS implementation


GeneralSystem.Diagnostics.Stopwatch() Pin
Jinx10125-Mar-07 7:31
memberJinx10125-Mar-07 7:31 
GeneralRe: System.Diagnostics.Stopwatch() Pin
Andy Missico20-May-10 11:16
memberAndy Missico20-May-10 11:16 
GeneralGreat post Pin
Jinx10123-Mar-07 17:21
memberJinx10123-Mar-07 17:21 
GeneralAccurate RT timing of User Response needed Pin
ian_s66628-Jan-07 9:17
memberian_s66628-Jan-07 9:17 
GeneralScreen Resolution Pin
Wahaj Khan7-Jan-05 20:11
memberWahaj Khan7-Jan-05 20:11 
GeneralExtra Code Pin
VectorX3-Jul-04 16:50
memberVectorX3-Jul-04 16:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170326.1 | Last Updated 28 Nov 2002
Article Copyright 2002 by Alastair Dallas
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid