How to calculate elapsed time of a function?

2019-02-06 03:55发布

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.

4条回答
混吃等死
2楼-- · 2019-02-06 04:29

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?).

查看更多
3楼-- · 2019-02-06 04:32

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;
查看更多
仙女界的扛把子
4楼-- · 2019-02-06 04:37

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
查看更多
Melony?
5楼-- · 2019-02-06 04:53
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;
查看更多
登录 后发表回答