萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Delphi 高精度計時三大方案對比:GetTickCount、DateUtils、QueryPerformanceCounter

前言:為什麼需要高精度計時?

效能分析、遊戲迴圈、即時控制、基準測試等場景需要微秒/毫秒級計時。Delphi 提供三種不同精度與適用場景的計時方案。

方案一:GetTickCount / GetTickCount64 (毫秒級,系統啟動後累計)

var
  StartTick, EndTick: DWORD; // 或 UInt64 (GetTickCount64)
  ElapsedMs: DWORD;
begin
  StartTick := GetTickCount; // 或 GetTickCount64 (Win XP+)
  Sleep(1000); // 模擬待測代碼
  EndTick := GetTickCount;
  ElapsedMs := EndTick - StartTick; // 自動處理 49.7 天溢位 (GetTickCount64 無溢位)
  ShowMessage('耗時: ' + IntToStr(ElapsedMs) + ' ms');
end;

特點:系統全域單調遞增、無需初始化、精度 ~10-16ms (系統時鐘中斷週期)、不適合 亞毫秒測量。

方案二:DateUtils 單元 (秒/毫秒級,TDateTime 基礎)

uses DateUtils;

var
  StartT, EndT: TDateTime;
  ElapsedSec, ElapsedMs: Int64;
begin
  StartT := Now; // 精度 ~1ms (實際依系統時鐘)
  Sleep(1000);
  EndT := Now;
  ElapsedSec := SecondsBetween(EndT, StartT);        // 秒差
  ElapsedMs  := MilliSecondsBetween(EndT, StartT);   // 毫秒差
  ShowMessage(Format('秒: %d, 毫秒: %d', [ElapsedSec, ElapsedMs]));
end;

特點:語意清晰、支援日期時間運算、精度同 GetTickCount 受限於系統時鐘解析度 (~1ms 以上)。

方案三:QueryPerformanceCounter (高精度,硬體計數器,微秒/奈秒級)

黃金標準,適用於效能分析、遊戲引擎、科學計算。

var
  Freq, StartCnt, EndCnt: Int64;
  ElapsedSec, ElapsedMs, ElapsedUs: Double;
begin
  // 1. 取得頻率 (每秒計數次數),程式啟動時查詢一次即可
  if not QueryPerformanceFrequency(Freq) then begin
    ShowMessage('硬體不支援高精度計時器');
    Exit;
  end;

  // 2. 開始計數
  QueryPerformanceCounter(StartCnt);
  Sleep(1000); // 待測代碼
  QueryPerformanceCounter(EndCnt);

  // 3. 計算 (雙精度浮點數避免溢位)
  ElapsedSec := (EndCnt - StartCnt) / Freq;
  ElapsedMs  := ElapsedSec * 1000;
  ElapsedUs  := ElapsedSec * 1_000_000;

  ShowMessage(Format('秒: %.6f, 毫秒: %.3f, 微秒: %.0f', [ElapsedSec, ElapsedMs, ElapsedUs]));
end;

三大方案對比表

特性GetTickCountDateUtils (Now)QueryPerformanceCounter
精度~10-16 ms~1-10 ms~0.1-1 µs (視 CPU 頻率)
溢位週期49.7 天 (DWORD) / 無 (QPC64)無 (TDateTime 為 Double)極長 (Int64 @ 3GHz ≈ 194 年)
跨進程同步是 (系統全域)是 (系統時間)否 (各 CPU 核心可能不同步,需 SetThreadAffinityMask)
適用場景粗略超時、簡單延遲日期時間差、日誌時間戳效能分析、高頻迴圈、遊戲幀率
開銷極低低低 (單指令 RDTSC/PMU)

封裝為可重用類別:TStopwatch

type
  TStopwatch = record
  private
    FStart, FStop, FFreq: Int64;
    FRunning: Boolean;
    class function GetFreq: Int64; static;
  public
    class function StartNew: TStopwatch; static;
    procedure Start;
    procedure Stop;
    function ElapsedMilliseconds: Int64;
    function ElapsedMicroseconds: Int64;
    function ElapsedTicks: Int64;
    property IsRunning: Boolean read FRunning;
  end;

class function TStopwatch.GetFreq: Int64;
var
  F: Int64;
begin
  if not QueryPerformanceFrequency(F) then F := 1000000; // 回退 1MHz
  Result := F;
end;

class function TStopwatch.StartNew: TStopwatch;
begin
  Result.FFreq := GetFreq;
  QueryPerformanceCounter(Result.FStart);
  Result.FRunning := True;
end;

procedure TStopwatch.Start;
begin
  if not FRunning then begin
    QueryPerformanceCounter(FStart);
    FRunning := True;
  end;
end;

procedure TStopwatch.Stop;
begin
  if FRunning then begin
    QueryPerformanceCounter(FStop);
    FRunning := False;
  end;
end;

function TStopwatch.ElapsedTicks: Int64;
var
  Current: Int64;
begin
  if FRunning then QueryPerformanceCounter(Current) else Current := FStop;
  Result := Current - FStart;
end;

function TStopwatch.ElapsedMilliseconds: Int64;
begin
  Result := (ElapsedTicks * 1000) div FFreq;
end;

function TStopwatch.ElapsedMicroseconds: Int64;
begin
  Result := (ElapsedTicks * 1_000_000) div FFreq;
end;

// 使用範例
var SW: TStopwatch;
begin
  SW := TStopwatch.StartNew;
  DoHeavyWork;
  SW.Stop;
  WriteLn('耗時 ', SW.ElapsedMilliseconds, ' ms / ', SW.ElapsedMicroseconds, ' µs');
end;

結語

  • **一般業務邏輯超時/延遲**:GetTickCount64 簡單可靠
  • **日期時間差值/日誌**:DateUtils.MilliSecondsBetween 語意最清晰
  • **效能分析/高精度需求**:唯有 QueryPerformanceCounter,並封裝為 TStopwatch 供專案統一使用

Delphi 10.10+ 內建 System.Diagnostics.TStopwatch,直接使用即可,無需自行實作。

copyright © 萬盛學電腦網 all rights reserved