Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate elapsed time of a function?

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.

like image 689
Hidden Avatar asked Jun 07 '13 12:06

Hidden


People also ask

What is the formula to find elapsed time?

In simple words, we can say that the amount of time that has passed between the beginning and the end of an event is called the elapsed time. We can determine this time by subtracting the end time and the start time. The formula to calculate the elapsed time is simply to subtract the hours and minutes separately.

What is example of elapsed time?

Definition of Elapsed Time Elapsed time is the amount of time that passes between the beginning and the end of an event. For example, Vernon ran a marathon in 2 hours and 15 minutes. He crossed the finish line at 10:30 a.m. What time did the race start?

What is elapse time?

Elapsed time in simple terms is the amount of time that passes from the start of an event to its end.


3 Answers

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;
like image 103
David Heffernan Avatar answered Oct 18 '22 19:10

David Heffernan


You can use the QueryPerformanceCounter and QueryPerformanceFrequency functions:

var
  c1, c2, f: Int64;
begin
  QueryPerformanceFrequency(f);
  QueryPerformanceCounter(c1);
  DoSomething;
  QueryPerformanceCounter(c2);

  // Now (c2-c1)/f is the duration in secs of DoSomething
like image 35
Andreas Rejbrand Avatar answered Oct 18 '22 18:10

Andreas Rejbrand


For the sake of having more possibilities for tackling the question, you could also use System.Classes.TThread.GetTickCount to get a current time in milliseconds to start your timer before your method, and then again after your method. The difference between these two is obviously the elapsed time in milliseconds, which you could transform into hours, seconds, etc.

Having said that, David Heffernan's proposal with TStopwatch is more elegant (and more precise?).

like image 41
Stormbringer Avatar answered Oct 18 '22 18:10

Stormbringer