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


本文整理自网络,侵删。

 
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 tfilestream流操作1

Delphi反调试【初级】检测法

Delphi rgb 画出三角形

Delphi xe5 unicodestring的由来

Delphi 三种方式读取txt文本文件

Delphi 取得文件夹及下一级文件夹下的文件列表

Delphi unigui http url直接下载文件

Delphi trimright 删除字符串右边的空格

Delphi使用project manager添加一个java库到你的应用程序

Delphi xe5 json

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



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...