VBfx / Common / GetTickCount

Introduction

When starting most people use the Timer control to move things around and do animation stuff. I call this Timer evil because it sucks in many points. Timers are quite slow and (since it's a control) resource-eating things. Of course there really are situations where a Timer control can get handy, but this surely won't be in any games or serious application (except probably in the Credits screen)! On this website however you won't find any Timers at all. Instead I'll show you how to use GetTickCount to perform accurate timing.

Get tick count

So what does GetTickCount do? Well in fact it's returning the number of ticks since your computer is running where one tick is 1 ms (1/1000 seconds). So what is this good for? Surely not for measuring how long your computer is running! What we can do is measuring difference between 2 ticks, see the following illustration:

Imagine the red mark being the current GetTickCount, around 375 ms. Now we want to set up a timed event that happens in 100 ms, so we add GettickCount (which is 375) + 100 = 475 in the example (blue mark). What we have to do now is calling GetTickCount again and again until it steps over the blue mark - when this happens the 100 ms are over.

Code it

So how can we do this in code? I'll show you a quite small example, just start a new project and add a CommandButton to your Form.

What the code does: When clicking the button we add a certain delay (like 1000 which is 1 second) to the current GetTickCount and wait until the time is over, then show a MessageBox. Now here's the code:

Private Declare Function GetTickCount Lib "kernel32" () as Long

This is the declaration of GetTickCount. We need to do this because it's a API call VB doesn't know. Note that it's declared Private so you can put it into the Form directly!

Private Sub Command1_Click()
    Dim NextTick as Long
    
    'Get current tick and add a delay
    NextTick = GetTickCount + 1000 '1 second
    
    'While the requested time is "in the future"
    While NextTick > GetTickCount
        'Wait
        DoEvents
    Wend
    
    'Show message
    MsgBox "1 second is over!", vbInformation
End Sub

Conclusion

GetTickCount provides you accurate timing and can be included in code directly (without any controls), therefore you should use it whenever possible which again means: always. The sample code shows you how to implement a execution delay in 3 lines of code, however there are several other ways to use GetTickCount. Just remember how to add delays to GetTickCount so you can compare them later in code. I recommend you to keep the time-line picture in mind, will help you working with this API!

Navigation