gpt4 book ai didi

delphi - 使用 `TStopWatch` 而不使用 `free`

转载 作者:行者123 更新时间:2023-12-03 15:20:56 27 4
gpt4 key购买 nike

我在 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 is not a class but still requires explicit initialization [using StartNew or Create methods].

这很令人困惑。我在函数中使用 TStopWatch,但没有使用 free。该函数可能会在每个 session 期间被调用多次(可能数百次,具体取决于使用情况)。这意味着将创建多个 TTopWatch 实例,但不会被释放。

是否有可能出现内存泄漏或其他并发症?如果答案是肯定的,我该怎么办?我是否必须为每个应用程序仅创建一个 TTopWatch 实例?或者我应该使用其他功能?还是别的什么?

最佳答案

链接的示例是基于类的 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);

关于delphi - 使用 `TStopWatch` 而不使用 `free`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50279598/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com