close

Window Api

QueryPerformanceFrequency

說明連結  https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancefrequency

以下簡稱 CPU頻率?

 

QueryPerformanceCounter

說明連結 https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter

以下簡稱 時間戳記

 

取得當前時間 微秒 原理如下

1. 系統啟動時取得系統啟動的時間戳記 及 當前時間

2. 當要取得時間時 取得當前的時間戳記

3. 已CPU頻率可將當前時間戳記算成已經過的時間(豪秒)

4. 將已經過的毫秒加上系統啟動時間即可得到約略的當前時間 豪秒單位

 

程式碼如下

 

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, DateUtils, Vcl.ExtCtrls;

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    Timer1: TTimer;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
  private
    FStartTime: TDateTime;  //系統啟動的時間
    FStartC: Int64;         //系統啟動時CPU以運行多少TICK
    FC: TLargeInteger;      //CPU一毫秒內的震動次數
    { Private declarations }
  public
    function GetNowTime: string; //取得當前時間
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function TForm1.GetNowTime: string; //取得當前時間
var
  t2:int64;
  n, ms, ns: Int64;
  G_Now: TDateTime;
begin
  QueryPerformanceCounter(t2); //獲取當前CPU已震動次數
  n := Round((t2-FStartC)/FC*1000000); //算出系統啟動到現在經過的時間 (微秒)
  ms := n div 1000; //取得n的豪秒部分
  ns := n mod 1000; //取得n的微秒部分

  //使用IncMilliSecond 用啟動時間 + 經過時間 算出當前時間 uses DateUtils
  Result := FormatDateTime('HH:NN:SS.ZZZ', IncMilliSecond(FStartTime, ms)) + Copy(IntToStr(ns) + '00', 1, 3);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Timer1.Enabled := not Timer1.Enabled;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  QueryPerformanceFrequency(FC);//WINDOWS API 返回计数频率(Intel86:1193180)(获得系统的高性能频率计数器在一毫秒内的震动次数)
  FStartTime := Now; //啟動時間
  QueryPerformanceCounter(FStartC); //系統啟動時的CPU已震動次數
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  Memo1.Lines.Append(GetNowTime + '||||' + FormatDateTime('HH:NN:SS.ZZZ', now));
end;

end.

arrow
arrow

    抓狂小白 發表在 痞客邦 留言(0) 人氣()