Re: How to time the execution of a method?



Here is a general timimg unit I use. Just put StartPeriod in your code
at the start point, and EndPeriod at the end, and then access the
result.

unit QPTimerU;

interface

uses
Windows ;

type
TTimeType = (ttSecs, ttMilliSecs, ttMicroSecs);

procedure StartPeriod;
procedure EndPeriod;
function ScaleTime(TimeSecs : double; TimeType : TTimeType) : double;

var
ElapsedCount : DWord;
ElapsedTime : double;

implementation


var
TempQPC, QPF, StartQPC : TLargeInteger;
OverHeadCount : extended;

function LargeIntToExt(LI : TLargeInteger) : extended;
const
Num : extended = $10000;
begin
{$IFDEF VER100}
Result := (LI.HighPart * Num * Num) + LI.LowPart; // Delphi 3
{$ELSE}
Result := (LARGE_INTEGER(LI).HighPart * $10000 * $10000) +
LARGE_INTEGER(LI).LowPart;
{$ENDIF}
end;

function ScaleTime(TimeSecs : double; TimeType : TTimeType) : double;
begin
Result := TimeSecs;
while TimeType > ttSecs do begin
Result := Result * 1000;
dec(TimeType);
end;
end;

procedure StartPeriod;
begin
QueryPerformanceCounter(StartQPC); // for overhead calc
QueryPerformanceCounter(TempQPC);
OverHeadCount := LargeIntToExt(TempQPC) - LargeIntToExt(StartQPC);
QueryPerformanceCounter(StartQPC); // real start time
end;

procedure EndPeriod;
var
EndQPC : TLargeInteger;
EndCount : extended;
StartCount : extended;
begin
QueryPerformanceCounter(EndQPC);
EndCount := LargeIntToExt(EndQPC);
StartCount := LargeIntToExt(StartQPC);
ElapsedCount := trunc(EndCount - StartCount - OverHeadCount);
QueryPerformanceFrequency(QPF);
ElapsedTime := ElapsedCount / LargeIntToExt(QPF);
end;

(*
// / / / / / / / / / / / /
// U s a g e
// / / / / / / / / / / / /

uses
QPTimerU;

procedure TForm1.StartBtnClick(Sender: TObject);
begin
StartPeriod;
end;

procedure TForm1.StopBtnClick(Sender: TObject);
begin
EndPeriod;
Label1.Caption := Format('%d counts', [ElapsedCount]);
Label2.Caption := Format('%6f secs', [ScaleTime(ElapsedTime,
ttSecs)]);
Label3.Caption := Format('%3f millisecs', [ScaleTime(ElapsedTime,
ttMilliSecs)]);
Label4.Caption := Format('%d microsecs',
[trunc(ScaleTime(ElapsedTime, ttMicroSecs))]);
end;
*)
end.

Alan Lloyd

.