【发布时间】:2013-06-07 12:39:06
【问题描述】:
我想知道如何在 Delphi 中计算一个函数所消耗的时间。
然后我想显示使用时间并与另一个函数或组件进行比较,以便知道更快的函数。
【问题讨论】:
标签: delphi function time delphi-xe3
我想知道如何在 Delphi 中计算一个函数所消耗的时间。
然后我想显示使用时间并与另一个函数或组件进行比较,以便知道更快的函数。
【问题讨论】:
标签: delphi function time delphi-xe3
您可以使用来自System.Diagnostics 单元的TStopwatch 来使用系统的高分辨率性能计数器来测量经过的时间。
var
Stopwatch: TStopwatch;
Elapsed: TTimeSpan;
....
Stopwatch := TStopwatch.StartNew;
DoSomething;
Elapsed := Stopwatch.Elapsed;
要读取以秒为单位的时间值,例如,从时间跨度读取,请执行以下操作:
var
Seconds: Double;
....
Seconds := Elapsed.TotalSeconds;
【讨论】:
import System.TimeSpan 才能成功使用Elapsed: TTimeSpan。
import 不是delphi。
您可以使用QueryPerformanceCounter 和QueryPerformanceFrequency 函数:
var
c1, c2, f: Int64;
begin
QueryPerformanceFrequency(f);
QueryPerformanceCounter(c1);
DoSomething;
QueryPerformanceCounter(c2);
// Now (c2-c1)/f is the duration in secs of DoSomething
【讨论】:
QueryPerformanceFrequency 的调用,或者您忘记了将滴答计数距离除以获得的频率。
TStopWatch。 [+1]
TStopWatch 可在此处作为课程使用,How to Accurately Measure Elapsed Time Using High-Resolution Performance Counter。
为了有更多解决问题的可能性,您还可以使用System.Classes.TThread.GetTickCount 获取当前时间(以毫秒为单位),以便在您的方法之前启动您的计时器,然后在您的方法之后再次启动。这两者之间的区别显然是以毫秒为单位的经过时间,您可以将其转换为小时、秒等。
话虽如此,David Heffernan 与TStopwatch 的提议更优雅(也更精确?)。
【讨论】:
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;
【讨论】: