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.
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.
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?
Elapsed time in simple terms is the amount of time that passes from the start of an event to its end.
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;
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
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?).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With