使用`TStopWatch`没有'free`

问题描述 投票:2回答:1

我在德尔福10.2东京使用TStopWatch进行高精度计时。

本网站:https://www.thoughtco.com/accurately-measure-elapsed-time-1058453给出了以下示例:

 var
  sw : TStopWatch;
  elapsedMilliseconds : cardinal;
begin
  sw := TStopWatch.Create() ;
  try
    sw.Start;
    //TimeOutThisFunction()
    sw.Stop;
    elapsedMilliseconds := sw.ElapsedMilliseconds;
  finally
    sw.Free;
  end;
end;

显然,那里有一个错误,因为:

  • StopWatch不包含Free
  • Delphi文档明确指出:

TStopwatch不是一个类,但仍然需要显式初始化[使用StartNewCreate方法]。

这令人困惑。我在函数中使用TStopWatch,我没有使用free。在每个会话期间可以多次调用此函数(可能数百次,具体取决于用法)。这意味着将创建TStopWatch的多个实例,而不会被释放。

是否存在内存泄漏或其他并发症的可能性?如果答案是肯定的,我该怎么办?我是否必须为每个应用程序仅创建一个TStopWatch实例?或者我应该使用其他功能?或者是其他东西?

delphi timer stopwatch
1个回答
7
投票

链接的示例是基于类的TStopWatch

unit StopWatch;
interface
uses 
  Windows, SysUtils, DateUtils;

type 
  TStopWatch = class
  ...

它是在德尔福推出基于TStopWatch的记录之前发布的。

由于类变体需要在使用后调用Free,并且基于记录没有,所以这里没有混淆。

只需继续使用基于Delphi记录的TStopWatch,无需在使用后释放它。

通常我使用以下模式:

var
  sw : TStopWatch;
begin
  sw := TStopWatch.StartNew;
  ... // Do something
  sw.Stop;
  // Read the timing
  WriteLn(sw.ElapsedMilliseconds);  
© www.soinside.com 2019 - 2024. All rights reserved.