Delphi D10.X 并行库PPL编程之 TParallel.For

2022-11-16 12:43:31 作者:admin

本文整理自网络,侵删。

 Delphi D10.X 并行库PPL编程系列之 TParallel.For
delphi中的RTL(运行库)提供了并行编程库(PPL --Parallel Programming Library) ,让您的应用程序可以在跨平台应用中有效的使用多个CPU并行运行任务的能力。使用TParallel.For 使循环更快。
TParallel.For说明
TParallel.For通过指定的整数索引值进行迭代,对每次迭代都调用事件处理程序,在并行线程中执行这些调用的程序。迭代器事件是否在并行线程中处理取决于可用的线程资源和性能。为了表示他与常规的For是一样的功能,TParallel.For同样也使用了For的名称,但TParallel.For使用的是并行执行方式,而不象常规for循环一样一个接一个地串行执行。
TParallel.For演示

unit Unit1;
interface
uses  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type  TForm1 = class(TForm)    Button1: TButton;    Button2: TButton;    Memo1: TMemo;    procedure Button1Click(Sender: TObject);    procedure Button2Click(Sender: TObject);  private    { Private declarations }  public    { Public declarations }  end;
var  Form1: TForm1;
implementation
{$R *.dfm}
uses  System.Threading, // 需要引用PPL库  System.Diagnostics,  System.SyncObjs;
  const  Max =5000000;

  //演示用的执行计算的函数function IsPrime(N: Integer): Boolean;var  Test, k: Integer;begin  if N <= 3 then    IsPrime := N > 1  else if ((N mod 2) = 0) or ((N mod 3) = 0) then    IsPrime := False  else  begin    IsPrime := True;    k := Trunc(Sqrt(N));    Test := 5;    while Test <= k do    begin      if ((N mod Test) = 0) or ((N mod (Test + 2)) = 0) then      begin        IsPrime := False;        break; { 跳出for循环 }      end;      Test := Test + 6;    end;  end;end;

procedure TForm1.Button1Click(Sender: TObject);
var  I, Tot: Integer;  SW: TStopwatch;begin    // 计算低于给定值的质数   Tot:=0;   SW := TStopWatch.Create;   SW.Start;   for I := 1 to Max do   begin     if IsPrime(I) then        Inc(Tot);   end;   SW.Stop;   Memo1.Lines.Add(Format('顺序For循环。 时间(以毫秒为单位):%d - 找到质数:%d', [SW.ElapsedMilliseconds,Tot]));
end;
procedure TForm1.Button2Click(Sender: TObject);var  Tot: Integer;  SW: TStopwatch;begin     try     // 计算低于给定值的质数       Tot :=0;       SW :=TStopWatch.Create;       SW.Start;       TParallel.For(2,1,Max,procedure(I:Int64)       begin         if IsPrime(I) then          TInterlocked.Increment(Tot);       end);     SW.Stop;      Memo1.Lines.Add(Format('并行循环。 时间(以毫秒为单位):%d - 找到质数:%d', [SW.ElapsedMilliseconds,Tot]));     except on E:EAggregateException do      ShowMessage(E.ToString);     end;
end;
end.

https://blog.csdn.net/tanqth/article/details/104552520

相关阅读 >>

Delphi不占cpu的延时函数

Delphi 取出一个字符在字符串出现的次数

Delphi uses 子句的写法

Delphi idhttp下载带清理网络缓存

Delphi 显示选择文件夹对话框 (有新建按钮)

如何在 Delphi 中静态链接 sqlite

Delphi调用createprocess创建进程

Delphi 去掉mdi窗口的滚动条

Delphi生成随机字符串

Delphi 实现批量文件名修改

更多相关阅读请进入《Delphi》频道 >>



在线咨询 拨打电话