31-07-2009, 08:32 PM
As you probably know, DoEvents is a very useful function built-in to VB allowing us to give our applications some 'fresh air' when they are doing intensive operations, such as loops. DoEvents works by checking for any other event that might need to run at the time, and then runs it. The only problem is DoEvents checks many useless events that we might not even need.
Basically, we are 're-making' the DoEvents function to check only for certain messages, such as keyboard input, mouse input and painting the screen.
Just copy paste the following in any module :
To make sure this actually optimized the function, I decided to do a benchmark. I opened up a blank VB app, put two controls and basically made a loop that would set the caption of one of the buttons to the current loop index. This is the code I used for the benchmark :
And the results were :
So as you can see, it definitely is a fairly important improvement to the function, and should let your loops that use DoEvents run much faster while still allowing user input
Basically, we are 're-making' the DoEvents function to check only for certain messages, such as keyboard input, mouse input and painting the screen.
Just copy paste the following in any module :
Code:
Private Declare Function GetQueueStatus Lib "user32" (ByVal fuFlags As Long) As Long
Public Const nLng As Long = (&H80 Or &H1 Or &H4 Or &H20) + (&H8 Or &H40)
Public Sub NewDoEvents()
If GetQueueStatus(nLng) 0 Then DoEvents
End Sub
To make sure this actually optimized the function, I decided to do a benchmark. I opened up a blank VB app, put two controls and basically made a loop that would set the caption of one of the buttons to the current loop index. This is the code I used for the benchmark :
Code:
Dim I As Long, Tick As Long
Tick = GetTickCount
For I = 1 To 1000000
Command1.Caption = I
Next I
Text1.Text = (GetTickCount - Tick)
Tick = GetTickCount
For I = 1 To 1000000
Command1.Caption = I
DoEvents
Next I
Text2.Text = (GetTickCount - Tick)
Tick = GetTickCount
For I = 1 To 1000000
Command1.Caption = I
NewDoEvents
Next I
Text3.Text = (GetTickCount - Tick)
And the results were :
Code:
Test 1
No DoEvents whatsoever - 15694 Ticks
Old DoEvents - 97875 Ticks
New DoEvents - 17004 Ticks
Test 2
No DoEvents whatsoever -7238
Old DoEvents -109528
New DoEvents - 7800
So as you can see, it definitely is a fairly important improvement to the function, and should let your loops that use DoEvents run much faster while still allowing user input
