2018/06/01

Delphi Base Class - TProc (CHT)

圖片來源

TProc 在 Delphi 的宣告是:
1
2
3
4
5
TProc = reference to procedure;
TProc<T> = reference to procedure (Arg1: T);
TProc<T1,T2> = reference to procedure (Arg1: T1; Arg2: T2);
TProc<T1,T2,T3> = reference to procedure (Arg1: T1; Arg2: T2; Arg3: T3);
TProc<T1,T2,T3,T4> = reference to procedure (Arg1: T1; Arg2: T2; Arg3: T3; Arg4: T4);


最近在寫測速程式時突然應用到它,我是這麼寫的:


function RunLongTime(AProc: TProc): Int64;
 var
  sw : TStopWatch;
begin
  sw := TStopWatch.Create() ;
  try
    sw.Start;
    AProc;
    sw.Stop;
    Result := sw.ElapsedMilliseconds;
  finally
  end;
end;

如此一來,任何想知道要執行時間的程式全都可以丟到這裡來,像是:

procedure ExportXLSX;
var
  LPos01: Integer;
  LGUID: TGUID;
begin
  // Open Excel OLE
  ExcelFile :=  CreateOleObject('Excel.Application');
  ExcelFile.DisplayAlerts := False;
  // Handle WoorkBook
  if not VarIsNull(ExcelFile) then begin
    WorkBook := ExcelFile.WorkBooks.Add;
      if not VarIsNull(WorkBook) then begin
      // Handle Sheet
          WorkSheet := WorkBook.WorkSheets[1];
      end;
    for LPos01 := 1 to StrToInt(Edit1.Text) do
    begin
      WorkSheet.Cells(LPos01, 1) := LPos01;
      LGUID := TGUID.NewGuid;
      WorkSheet.Cells(LPos01, 2) := LGUID.ToString;
    end;
    WorkSheet.SaveAs('hello.xlsx');
    ExcelFile.Quit;
    ExcelFile := Unassigned;
  end;
end;
這段是Excel的操作,要測試可以執行多久,可以這樣寫:
Result := (RunLongTime( ExportXLSX));

剩下的就留給您體驗看看!

See also:




沒有留言:

張貼留言