delphitimerstopwatch

Using `TStopWatch` without `free`


I am using TStopWatch for high-precision timekeeping in Delphi 10.2 Tokyo.

This website: https://www.thoughtco.com/accurately-measure-elapsed-time-1058453 has given the following example:

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

Apparently, there is a mistake there, since:

TStopwatch is not a class but still requires explicit initialization [using StartNew or Create methods].

This is confusing. I am using TStopWatch in a function, and I am not using free. This function may be called multiple times during each session (perhaps hundreds of times, depending on the usage). It means multiple instances of TStopWatch will be created, without being freed.

Is there a possibility of memory leaks, or other complications? If the answer is yes, what am I supposed to do? Do I have to create only one instance of TStopWatch per application? Or should I use other functions? Or something else?


Solution

  • The linked example is a TStopWatch based on a class.

    unit StopWatch;
    interface
    uses 
      Windows, SysUtils, DateUtils;
    
    type 
      TStopWatch = class
      ...
    

    It was published before Delphi introduced the record based TStopWatch.

    Since the class variant needs to call Free after use, and the record based does not, there is no confusion here.

    Just continue using the Delphi record based TStopWatch without a need to free it after use.

    Usually I use the following pattern:

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