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

标签 delphi timer stopwatch

我在 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/

相关文章:

delphi - 使用 Delphi 将数据发送到 PDF

delphi - 将数据写入I/O地址

go - rpc方法的定时器实现

timer - STM32F030 PWM 设置问题

c# - 如何编写一个函数来确定一个键是否按下并经过延迟?

Delphi 2007 调试器不见了

android - 每 10 分钟在后台执行一次数据库操作

python - 时间不准确或代码效率低下?

r - 秒表作为 shiny for R 的输入

arrays - 如何从Delphi函数返回数组?