Tools Links Login

No CPU Load - SafeSleep

The *BEST* way to safely Sleep/Pause without taxing the CPU.

Original Author: Steve Gaeke

Code


The two functions below both sleep for the specified number of seconds. However, the popular code seen in the BusySleep procedure actually causes the CPU load to stay near 100% until complete. The SafeSleep routine pauses without taxing the CPU and stays at nearly 0% CPU.
Both functions take a single value so you can sleep for fractions of a second.





Private Declare Function MsgWaitForMultipleObjects Lib "user32" (ByVal nCount As Long, pHandles As Long, ByVal fWaitAll As Long, ByVal dwMilliseconds As Long, ByVal dwWakeMask As Long) As Long


Public Sub SafeSleep(ByVal inWaitSeconds As Single)

Const WAIT_OBJECT_0 As Long = 0

Const WAIT_TIMEOUT As Long = &H102



Dim lastTick As Single

Dim timeout As Long

timeout = inWaitSeconds * 1000

lastTick = Timer



Do

Select Case MsgWaitForMultipleObjects(0, 0, False, timeout, 255)

Case WAIT_OBJECT_0

  DoEvents

  timeout = ((inWaitSeconds) - (Timer - lastTick)) * 1000

  If timeout < 0 Then timeout = 0



Case Else

  Exit Do


  
End Select



Loop While True



End Sub


Public Sub BusySleep(ByVal inWaitSeconds As Single)

Dim lastTick As Single


lastTick = Timer



Do

DoEvents



Loop While (Timer - lastTick) < inWaitSeconds



End Sub


About this post

Posted: 2002-06-01
By: ArchiveBot
Viewed: 88 times

Categories

Visual Basic 6

Attachments

No attachments for this post


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.