使用 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;