»  The Delphi Column 

Timing a block of code

GetTickCount - for coarse timing

Probably the easiest way of timing a block of code is to call the function GetTickCount before entering the code block and calling it again on exit from the code block. The difference is the length of time the code took to execute.
var
var
  startTime, endTime: int64;
  i, Milliseconds: integer;
  N: double;
begin
  startTime := GetTickCount;
  for i := 1 to 5000000 do
    N := Sqrt(Random(i)); // or any block to time, e.g. FunctionToTime()
  endTime := GetTickCount;
  Milliseconds := endTime - startTime;
  Label1.Caption := IntToStr(Milliseconds);
end;
Don't rely on Now() for short time intervals: they have an interval of about 10ms (depending on your Windows version). So the duration of "your code to test" can give 0ms.

QueryPerformanceCounter - for accurate timing

QueryPerformanceFrequency retrieves the frequency of the high-resolution performance counter, if one exists. This frequency doesn't change while the system is running.
var
  Frequency, StartCount, StopCount: int64;
  i: integer;
  N, Milliseconds: double;
begin
  QueryPerformanceFrequency(Frequency);
  QueryPerformanceCounter(StartCount);
  for i := 1 to 5000000 do
    N := Sqrt(Random(i)); // or any block to time, e.g. FunctionToTime()
  QueryPerformanceCounter(StopCount);
  Milliseconds := 1000 * ((StopCount - StartCount) / Frequency);
  Label2.Caption := FloatToStr(Milliseconds);
end;


Database Tutorials  FAQ  Crash Course Delphi  Tips  Source Code  Downloads  Links

Copyright 1999-2022 
DelphiLand