使用 Windows API GetTickCount

Windows API GetTickCount 函式返回自系統(計算機)啟動以來的毫秒數。最簡單的例子如下:

var
  Start, Stop, ElapsedMilliseconds: cardinal;
begin
  Start := GetTickCount;
  // do something that requires measurement
  Stop := GetTickCount;
  ElapsedMillseconds := Stop - Start;
end;

請注意,GetTickCount 返回 32 位 DWORD,因此它每 49.7 天包裝一次。為避免包裝,你可以使用 GetTickCount64(自 Windows Vista 以來可用)或特殊例程來計算滴答差異:

function TickDiff(StartTick, EndTick: DWORD): DWORD;
begin
  if EndTick >= StartTick
    then Result := EndTick - StartTick
    else Result := High(NativeUInt) - StartTick + EndTick;
end;

function TicksSince(Tick: DWORD): DWORD;
begin
  Result := TickDiff(Tick, GetTickCount);
end;

無論如何,如果 GetTickCount 的兩個後續呼叫的間隔超過 49.7 天的邊界,這些例程將返回不正確的結果。

要將毫秒轉換為秒示例:

var
  Start, Stop, ElapsedMilliseconds: cardinal;
begin
  Start := GetTickCount;
  sleep(4000); // sleep for 4 seconds
  Stop := GetTickCount;
  ElapsedMillseconds := Stop - Start;
  ShowMessage('Total Seconds: '
      +IntToStr(round(ElapsedMilliseconds/SysUtils.MSecsPerSec))); // 4 seconds
end;