利用timeGetTime函數更精準地計算時間差

來源:互聯網
上載者:User
我想每 0.005 秒做某一件工作, 所以撰寫了以下程式:
Dim tm1 As Single
Do
tm1 = Timer
While Timer - tm1 < 0.005 ' 等於 0.005 秒
DoEvents
Wend
...做某一件工作
Loop

但實際上, 在 While 迴圈裡面, Timer 函數幾乎每次都得到相同的時間,只有大約隔了 0.05秒才會得到不同的時間, 也就是說 Timer 的準確性只有 0.05 秒,但我希望進行的工作卻是每 0.005 秒一次, 該怎麼辦呢?可以改用 Windows API 的 timeGetTime 函數, 此一函數會傳回 Windows 開機以來所經過的時間,時間單位是 1/1000 秒, 舉例來說, 開機經過 2 分鐘, 則傳回值等於 2*60*1000, timeGetTime 的優點是時間可以精確到 1/1000 秒, 所以可以用來解決上述的問題,細節如下:

1. API 的聲明:
Private Declare Function timeGetTime Lib "winmm.dll" Alias "timeGetTime"
() As Long
註:如果以上的聲明放在「一般模組」底下, 應將 Declare 之前的 Private 保
留字去掉。

2. 程式範例:
Dim tm1 As Long
Do
tm1 = timeGetTime
While timeGetTime - tm1 < 5 ' 等於 5/1000 = 0.005 秒
DoEvents
Wend
...做某一件工作
Loop

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.