1. 程式人生 > >Delphi高精度計時方法

Delphi高精度計時方法

//取毫秒級時間精度(方法一):
var
t1,t2:int64;
r1:int64;
begin
t1:=GetTickCount;//獲取開始計數 WINDOWS API
sleep(1000);{do...}//執行要計時的程式碼
t2:=GetTickCount;//獲取結束計數值
r1:=t2-t1;//取得計時時間,單位毫秒(ms)
showmessage(inttostr(r1));
end;
 

//取毫秒級時間精度(方法二):
//use DateUtils;//引用DateUtils單位
var
t1,t2:tdatetime;
r1:int64;
begin
t1:=now();//獲取開始計時時間
sleep(1000);{do...}//執行要計時的程式碼
t2:=now();//獲取結束計時時間
r1:=SecondsBetween(t2,t1);//取得計時時間,單位秒(s)
r1:=MilliSecondsBetween(t2,t1);//取得計時時間,單位毫秒(ms)
showmessage(inttostr(r1));
end;

//注:以上兩種方式經本人測試好像只能產生0.01秒的計時精度

//取系統級時間精度:
var
c1:int64;
t1,t2:int64;
r1:double;
begin
QueryPerformanceFrequency(c1);//WINDOWS API 返回計數頻率(Intel86:1193180)(獲得系統的高效能頻率計數器在一毫秒內的震動次數)
QueryPerformanceCounter(t1);//WINDOWS API 獲取開始計數值
sleep(1000);{do...}//執行要計時的程式碼
QueryPerformanceCounter(t2);//獲取結束計數值
r1:=(t2-t1)/c1;//取得計時時間,單位秒(s)
r1:=(t2-t1)/c1*1000;//取得計時時間,單位毫秒(ms)
r1:=(t2-t1)/c1*1000000;//取得計時時間,單位微秒
showmessage(floattostr(r1));
end;