Timing in Basic


Timing should be easy in Visual Basic. You get the start time from the Timer function, carry out the operation, and get the ending time. Subtract the start time from the end time, and you have the operation time. But in what units of time?


According to the Visual Basic documentation, Timer returns the number of seconds since midnight. You’d need a lot of iterations to get meaningful timing results if Timer actually returned whole seconds, but fortunately it returns seconds as a real number, nominally accurate to hundredths of a second. Actually, the Timer function is much less accurate—in fact, too inaccurate to be of much use. The sidebar “Better Basic Through Subclassing” tells how to replace the Timer function with your own better version.


Instead of Timer, I use a set of profile procedures, keeping them in DEBUG.BAS along with my debug procedures. As I do with the debug procedures, I use conditional compilation and various other debugging techniques so that the profile procedures can disappear in the release version of my program. (“Assert Yourself,” page 35, discusses issues of writing debugging code in more detail.) The design of the procedures is simple and not very interesting, so I’ll concentrate on how to use them.


Before timing an operation, you need to declare two Currency variables to contain the result:

Dim sec As Currency, secOut As Currency

“Large Integers and Currency,” page 62, tells how this works and explains the somewhat surrealistic practice of measuring seconds in Currency. You pass one of these variables to ProfileStart:

ProfileStart sec

ProfileStart gets the start time from the system and stores it in the argument variable. You do the operation and then pass the start time to ProfileStop, which calculates the duration and returns it in the second variable:

ProfileStop sec, secOut

You can use the result—secOut, in this case—in an expression or wherever you happen to need it.


You’re probably thinking that it would be more convenient to have ProfileStart and ProfileStop as functions rather than returning values through reference parameters. Maybe so, but I specifically designed them as subs to discourage calling them in expressions where they might cause side effects. “An Assertion Implementation,” page 37, describes another reason for writing debug procedures as subs.