Improved DoEvents For NT Users

Try adding a line with Sleep 1 after DoEvents to your tight loops, this will only cost you 1 ms and if you just call the sleep command every 150 or 200 passes, it doesn’t cost you much. On my PC the procedure below shows 1% or less change to my CPU usage. If you REM out the sleep line CPU usage hits 100% quick.

Declare

Private Declare Sub Sleep Lib "Kernel32" (ByVal dwmilliseconds As Long)

Sample Code

Private Sub Command1_Click()
Dim iCounter As Integer
    Do
        'Your Process
        For iCounter = 1 To 10000
            DoEvents
            ' 200 seems like a good value to ensure
            ' min. slow down with min. load on CPU usage
            ' according to NT 40's Task Manager
            ' the next line will cost you t ms for every
            ' 200 passes
            If iCounter Mod 200 = 0 Then
                Sleep 1
            End If
        Next
    Loop
End Sub

 

Tip Submitted By: Jim Lewey

 

Editors Note: On my NT machine, calling Sleep after every 200 loops put my CPU usage to about 92%. I dropped it to 10 and my usage went to 1%. Just beware of this… your mileage might vary.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.