您好我正在使用QueryperformanceCounter計時在Delphi的代碼塊。出於某種原因,使用QueryPerformanceCounter獲得的 毫秒數與通過使用秒錶的掛鐘時間完全不同。例如,秒錶給我大約33秒,這看起來不錯,如果不準確,但使用QueryPerofomanceCounter會給我一個數字,如500毫秒。爲什麼QueryperformanceCounter的時間與掛鐘不同?
當通過我的代碼步驟時,我可以看到QueryPerformanceFrequency爲我的CPU提供了正確的CPU頻率,爲Core2 E6600提供了2.4G的CPU頻率。所以如果打勾號是正確的,(tick number/Freq) * 1000
應該給我正確的代碼執行時間,我爲什麼不是?
我知道對於我試圖計時的代碼來說,QeuryPerformanceCounter可能是過度查殺,因爲它花費了幾秒而不是百萬秒,但我更感興趣的是瞭解掛鐘和QueryPerormanceCounter之間時差的原因。
我的硬件是E6600 Core2,OS是Windows 7 X64(如果它是相關的)。
unit PerformanceTimer;
interface
uses Windows, SysUtils, DateUtils;
type TPerformanceTimer = class
private
fFrequency : TLargeInteger;
fIsRunning: boolean;
fIsHighResolution: boolean;
fStartCount, FstopCount : TLargeInteger;
procedure SetTickStamp(var lInt : TLargeInteger) ;
function GetElapsedTicks: TLargeInteger;
function GetElapsedMiliseconds: TLargeInteger;
public
constructor Create(const startOnCreate : boolean = false) ;
procedure Start;
procedure Stop;
property IsHighResolution : boolean read fIsHighResolution;
property ElapsedTicks : TLargeInteger read GetElapsedTicks;
property ElapsedMiliseconds : TLargeInteger read GetElapsedMiliseconds;
property IsRunning : boolean read fIsRunning;
end;
implementation
constructor TPerformanceTimer.Create(const startOnCreate : boolean = false) ;
begin
inherited Create;
fIsRunning := false;
fIsHighResolution := QueryPerformanceFrequency(fFrequency) ;
if NOT fIsHighResolution then
fFrequency := MSecsPerSec;
if startOnCreate then
Start;
end;
function TPerformanceTimer.GetElapsedTicks: TLargeInteger;
begin
result := fStopCount - fStartCount;
end;
procedure TPerformanceTimer.SetTickStamp(var lInt : TLargeInteger) ;
begin
if fIsHighResolution then
QueryPerformanceCounter(lInt)
else
lInt := MilliSecondOf(Now) ;
end;
function TPerformanceTimer.GetElapsedMiliseconds: TLargeInteger;
begin
result := (MSecsPerSec * (fStopCount - fStartCount)) div fFrequency;
end;
procedure TPerformanceTimer.Start;
begin
SetTickStamp(fStartCount) ;
fIsRunning := true;
end;
procedure TPerformanceTimer.Stop;
begin
SetTickStamp(fStopCount) ;
fIsRunning := false;
end;
end.
我猜,顯示的代碼也將有所幫助有通過(1000錯乘)10^3^2的幅度差 –
只是做了一個小測試,一個單一的算術加操作甚至不會注意到的一個刻度一半時間。一個包含50個添加操作的循環將生成1或2個滴答。那麼使用QueryPerformanceCounter有什麼問題。 –
@pstar:50個添加操作並不是很多。 'QueryPerformanceCounter'確實沒有錯。請顯示您實際測量的代碼。 – jpfollenius