経過時間を得るには?

Windows (VCL) の場合だと、GetTickCount() API で経過時間を得られましたが、System.Diagnostics.TStopwatch レコードで得る事ができます。

uses
  ..., System.Diagnostics;

var
  Tick: Int64;
  sw: TStopWatch;
begin
  sw := TStopWatch.StartNew;
  Tick := sw.ElapsedMilliseconds;
  Sleep(500); // 500ms 待ってみる
  ShowMessage(IntToStr(sw.ElapsedMilliseconds - Tick));
end;

経過時間を再利用しないのならもっとシンプルに書けます。

uses
  ..., System.Diagnostics;

var
  sw: TStopWatch;
begin
  sw := TStopWatch.StartNew;
  Sleep(500); // 500ms 待ってみる
  ShowMessage(sw.Elapsed);
end;

※ TStopwatch は VCL からも利用可能です (2010 以降)。

TPlatformServices を使った取得方法もあります (XE3 以降)。

uses
  ..., FMX.Platform;

procedure TForm1.Button1Click(Sender: TObject);
var
  Tick: Extended;
  TimerService: IFMXTimerService;
begin
  if TPlatformServices.Current.SupportsPlatformService(IFMXTimerService, IInterface(TimerService)) then
    begin
      Tick := TimerService.GetTick;
      Sleep(500); // 500ms 待ってみる
      ShowMessage(FloatToStr(TimerService.GetTick - Tick));
    end;
end;

最初からサービスが利用可能だと判明している場合には TPlatformService のクラスメソッドを使って少し短く、かつ簡潔に記述できます。

XE2 の場合には、PlatForm 変数GetTick() メソッドで得る事ができます。

uses
  ..., FMX.Platform;

var
  Tick: Extended;
begin
  Tick := Platform.GetTick;
  Sleep(500); // 500ms 待ってみる
  ShowMessage(FloatToStr(Platform.GetTick - Tick));
end;

※ Platform 変数は XE3 (FM2) 以降では使えません。

See Also:


 BACK