delphi 使用不带“free”的“TStopWatch”

yebdmbv4  于 5个月前  发布在  PWA
关注(0)|答案(2)|浏览(63)

我在 Delphi 10.2 Tokyo中使用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示例吗?或者我应该使用其他函数?或者其他东西?

eni9jsuy

eni9jsuy1#

链接的示例是基于类的TStopWatch

unit StopWatch;
interface
uses 
  Windows, SysUtils, DateUtils;

type 
  TStopWatch = class
  ...

字符串
它是在 Delphi 引入基于记录的TStopWatch之前发布的。
由于类变量在使用后需要调用Free,而基于记录的不需要,所以这里没有混淆。
只需继续使用基于 Delphi 记录的TStopWatch,而不需要在使用后释放它。
我通常使用以下模式:

var
  sw : TStopWatch;
begin
  sw := TStopWatch.StartNew;
  ... // Do something
  sw.Stop;
  // Read the timing
  WriteLn(sw.ElapsedMilliseconds);

7fhtutme

7fhtutme2#

这是一个类,所以你需要自由。一个很好的模式是做测量时间只是一个备忘录或控制台,你运行它,直到你按下一个键:

sw:= TStopWatch.Create();
  try
    sw.Start;
    //TimeOutThisFunction()
    //sleep(500)
    memo2.setfocus;
    repeat until iskeypressed;
    sw.Stop;
    //elapsedMilliseconds:= sw.getValueStr; 
    writeln('stopwatch '+sw.getValueStr);
  finally
    sw.Free;
  end;

字符串

相关问题