Delphi 如何计算函数的运行时间?

Delphi 如何计算函数的运行时间?,delphi,function,time,delphi-xe3,Delphi,Function,Time,Delphi Xe3,我想知道如何在Delphi中计算函数所消耗的时间 然后我想显示使用的时间,并将其与另一个函数或组件进行比较,以了解更快的函数。您可以使用和函数: var c1, c2, f: Int64; begin QueryPerformanceFrequency(f); QueryPerformanceCounter(c1); DoSomething; QueryPerformanceCounter(c2); // Now (c2-c1)/f is the duration in

我想知道如何在Delphi中计算函数所消耗的时间

然后我想显示使用的时间,并将其与另一个函数或组件进行比较,以了解更快的函数。

您可以使用和函数:

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

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

您可以使用
System.Diagnostics
单元中的
TStopwatch
来使用系统的高分辨率性能计数器测量经过的时间

var
  Stopwatch: TStopwatch;
  Elapsed: TTimeSpan;
....
Stopwatch := TStopwatch.StartNew;
DoSomething;
Elapsed := Stopwatch.Elapsed;
要读取以秒为单位的时间值,请执行以下操作:

var
  Seconds: Double;
....
Seconds := Elapsed.TotalSeconds;
VAR-iffrequency,iTimerStart,iTimerEnd:Int64;
程序定时器启动;
开始
如果没有查询,则查询性能频率(IfFrequency)
然后发出警告(“高分辨率计时器不可用!”);
WinApi.Windows.QueryPerformanceCounter(iTimerStart);
结束;
复发功能时间:双;{以毫秒为单位}
开始
QueryPerformanceCounter(iTimerEnd);
结果:=1000*((iTimerEnd-iTimerStart)/ifrequency);
结束;
函数:字符串;{以秒/毫秒为单位}
开始
如果复发时间<1000
然后结果:=Real2Str(timerecursed,2)+“ms”
其他结果:=Real2Str(timerecursed/1000,2)+“s”;
结束;

为了有更多的可能性来解决这个问题,您还可以使用
System.Classes.TThread.GetTickCount
获取当前时间(以毫秒为单位),在方法之前启动计时器,然后在方法之后再次启动计时器。这两者之间的区别显然是以毫秒为单位的运行时间,您可以将其转换为小时、秒等


话虽如此,David Heffernan提出的关于TStopwatch的建议更优雅(更精确?)

秒还是毫秒?因为我有一个胡格号码。也许我做错了什么。。Ergebnis:=c2-c1;标签2.标题:=“Benötigte Zeit:”+IntToStr(Ergebnis);我得到了这个。。。看看“Benötigte Zeit”@Polymopin:可能吧。也许您忘记了调用
QueryPerformanceFrequency
,或者您忘记了将滴答数距离除以获得的频率。@Andreas,我个人建议使用Delphi XE3。[+1]@AndreasRejbrand,
TStopWatch
在这里作为一个类提供。可能是重复的。肯定是重复的,另一个候选人:是的,他也是我的英雄^ ^ david heffernan for Delphi 10西雅图你必须导入系统。TimeSpan另外,要成功使用
Essed:TTimeSpan
。不,你不能。这不是有效的Delphi。@DavidHeffernan System.TimeSpan不是有效的Delphi?@fmmatheus我想我指的是
import
不是Delphi。
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;