|
Over the years, I've certainly seen an awful lot of horribly lame methods to time VB code. The most common mistakes include:
- Using VB's own Timer function, with its clock-tick resolution of ~55ms,
- Timing too few iterations to make for meaningful comparisons,
- Including non-critical code that shouldn't be timed,
- Failing to subtract the time of loop overhead and other code that couldn't be eliminated, and
- Testing in the IDE rather than from a compiled EXE.
Published results that don't account for the above are worse than worthless. I've used the CStopWatch class for many years now, and would encourage others to use it as well, for consistent benchmarks. CStopWatch provides millisecond resolution on most PCs, by employing the multimedia timer call timeGetTime. Using it is almost too easy! Check out this example:
The results returned by CStopWatch are all in milliseconds, of course. Not a unit of measure humans often think in. To convert milliseconds to more intuitive output, especially for longer time periods, you could use a function such as this:
Public Function FormatHMS(Optional ShowDecimal As Boolean) As String Dim Rtn As String Dim e As Long ' This routine is useful to get a nicely formatted display of ' elapsed time for reports and such. Not a good one to call ' within tight loops, of course! e = Me.Elapsed Rtn = Format$(DateAdd("s", (e \ 1000), #12:00:00 AM#), "HH:MM:SS") If ShowDecimal Then Rtn = Rtn & "." & Format$(e Mod 1000, "000") FormatHMS = Rtn End FunctionI've actually added this function to the base class, on the recommendation of a reader, to make it easier to use. Many happy benchmarks!
This sample, or the one from which it originally derived, was published (or at least peripherally mentioned) in the following article(s):
- Customizing the Ride (Part 1), Classic VB Corner, VSM Online, April 2010
- Measuring Optimizations for Classic VB, Classic VB Corner, VSM Online, May 2010
This sample uses the following API calls:
Module Library Function CStopWatch.cls winmm timeBeginPeriod
timeEndPeriod
timeGetDevCaps
timeGetTimeFQueryPC.frm kernel32
user32QueryPerformanceCounter
QueryPerformanceFrequency
GetWindowLong
SendMessage
SetWindowLongDon't see what you're looking for? Here's a complete API cross-reference.
Please, enjoy and learn from this sample. Include its code within your own projects, if you wish. But, in order to insure only the most recent code is available to all, I ask that you don't share the sample by any form of mass distribution. Download StopWatch.zip, 19Kb, Last Updated: Monday, April 26, 2010