【问题标题】:How to calculate elapsed time of a function?如何计算函数的运行时间?
【发布时间】:2013-06-07 12:39:06
【问题描述】:

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

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

【问题讨论】:

标签: delphi function time delphi-xe3


【解决方案1】:

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

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

要读取以秒为单位的时间值,例如,从时间跨度读取,请执行以下操作:

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

【讨论】:

  • 是的,他也是我的英雄^_^
  • @david-heffernan for Delphi 10 Seattle 你必须另外import System.TimeSpan 才能成功使用Elapsed: TTimeSpan
  • 不,你没有。那不是有效的 Delphi。
  • @DavidHeffernan System.TimeSpan 不是有效的 Delphi?
  • @fmmatheus 我想我指的是import 不是delphi。
【解决方案2】:

您可以使用QueryPerformanceCounterQueryPerformanceFrequency 函数:

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

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

【讨论】:

  • 秒还是毫秒?因为我有一个huuuuge号码。
  • 嗯,也许我做错了什么? .. Ergebnis := c2-c1; Label2.Caption := 'Benötigte Zeit: ' + IntToStr(Ergebnis);我得到了这个......看看“Benötigte Zeit”db.tt/cEKKB0w5
  • @Polymorphin:可能。也许您忘记了对QueryPerformanceFrequency 的调用,或者您忘记了将滴答计数距离除以获得的频率。
  • @Andreas,我个人建议为 Delphi XE3 使用TStopWatch。 [+1]
  • @AndreasRejbrand,TStopWatch 可在此处作为课程使用,How to Accurately Measure Elapsed Time Using High-Resolution Performance Counter
【解决方案3】:

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

话虽如此,David Heffernan 与TStopwatch 的提议更优雅(也更精确?)。

【讨论】:

    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-19
      • 2021-07-15
      相关资源
      最近更新 更多