Mega Code Archive

 
Categories / Delphi / Functions
 

High Res Timer (API Function)

Title: High Res Timer (API - Function) Question: When Timer is not good enough Answer: Here's a method for calculating a function with the use of a highres timer. Procedure TForm1.Button1Click(Send: TObject); var loop1,loop2 : integer; startcount, endcount, frequency : TLargeInteger; Elapsedtime : Extended; Begin QueryPerformanceFrequency(Frequency) {retrieve the freq from highres timer if present} QueryPerformaceCounter(Startcount); {Start timing} For loop1 := 0 to 99 do for loop2 := 0 to 99 do StringGrid1.cells[loop2,loop1] := inttostr((loop1*100)+loop2); {do something here} QueryPerformanceCounter(Endcount); {End timing} Elapsedtime := (Endcount.Quadpart-Startcount.QuadPart)/Frequency.QuadPart; {Calculates total amount of time the function took to compleet} Label1.Caption := 'Elapsed time : '+FloatTostr(ElapsedTime)+' seconds.'; End; Keep in mind that this frequency varies from machine to machine. It all depends on the hardware configuration. It can be usefull for optimizing a part of your code. Not every machine has a highres timer. Here's some code to check if there is one. if QueryPerformanceCounter(frequency) then label1.Caption := 'High Res Timer present.'; else label1.Caption := 'No High Res Timer present.'; So happy timing!