How to calculate elapsed time of a function?

Hidden picture Hidden · Jun 7, 2013 · Viewed 25.3k times · Source

I would like to know how to calculate the time consumed for a function in Delphi.

Then I wanted to show the used time and compare it with another function or component so as to know the faster function.

Answer

David Heffernan picture David Heffernan · Jun 7, 2013

You can use TStopwatch from the System.Diagnostics unit to measure elapsed time using the system's high-resolution performance counter.

var
  Stopwatch: TStopwatch;
  Elapsed: TTimeSpan;
....
Stopwatch := TStopwatch.StartNew;
DoSomething;
Elapsed := Stopwatch.Elapsed;

To read a time value in seconds, say, from a time span, do this:

var
  Seconds: Double;
....
Seconds := Elapsed.TotalSeconds;