How to calculate elapsed time of a function?

2019-02-06 03:53发布

问题:

I would like to know how to calculate the time consumed for a function in Delphi.

Then I wanted to show the used time and compare it with another function or component so as to know the faster function.

回答1:

You can use TStopwatch from the System.Diagnostics unit to measure elapsed time using the system's high-resolution performance counter.

var
  Stopwatch: TStopwatch;
  Elapsed: TTimeSpan;
....
Stopwatch := TStopwatch.StartNew;
DoSomething;
Elapsed := Stopwatch.Elapsed;

To read a time value in seconds, say, from a time span, do this:

var
  Seconds: Double;
....
Seconds := Elapsed.TotalSeconds;


回答2:

You can use the QueryPerformanceCounter and QueryPerformanceFrequency functions:

var
  c1, c2, f: Int64;
begin
  QueryPerformanceFrequency(f);
  QueryPerformanceCounter(c1);
  DoSomething;
  QueryPerformanceCounter(c2);

  // Now (c2-c1)/f is the duration in secs of DoSomething


回答3:

For the sake of having more possibilities for tackling the question, you could also use System.Classes.TThread.GetTickCount to get a current time in milliseconds to start your timer before your method, and then again after your method. The difference between these two is obviously the elapsed time in milliseconds, which you could transform into hours, seconds, etc.

Having said that, David Heffernan's proposal with TStopwatch is more elegant (and more precise?).



回答4:

VAR iFrequency, iTimerStart, iTimerEnd: Int64;

procedure TimerStart;
begin
  if NOT QueryPerformanceFrequency(iFrequency)
  then MesajWarning('High resolution timer not availalbe!');
  WinApi.Windows.QueryPerformanceCounter(iTimerStart);
end;


function TimerElapsed: Double; { In miliseconds }
begin
  QueryPerformanceCounter(iTimerEnd);
  Result:= 1000 * ((iTimerEnd - iTimerStart) / ifrequency);
end;


function TimerElapsedS: string;       { In seconds/miliseconds }
begin
 if TimerElapsed < 1000
 then Result:= Real2Str(TimerElapsed, 2)+ ' ms'
 else Result:= Real2Str(TimerElapsed / 1000, 2)+ ' s';
end;