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 idhttp的基本用法

Delphi firedac,ado性能测试

Delphi-adoquery查询、插入、删除、修改

Delphi中动态加载treeview信息

Delphi中控件数组批量赋值

Delphi url编码与解码工具附代码

Delphi远程注入dll方法

Delphi 防止程序重复执行(多种方法)

Delphi xe 应用程序横竖屏设置

Delphi 控制台读写

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



打赏

取消

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

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

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

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

评论

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