频道分类

Delphi xe TParallel.For的用法

作者:admin 来源: 日期:2020/3/11 12:14:58 人气: 标签:

 
unit Unit18;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes,
  System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
  FMX.ScrollBox, FMX.Memo, FMX.Controls.Presentation, FMX.StdCtrls,
  System.Threading, System.Diagnostics, System.SyncObjs;
 //加黑的这三个单元需要手工加入,我想啊,如果代码中我写了TParallel.For能自动引用对应的单元就好了。

type
  TForm18 = class(TForm)
    btnForLoop: TButton;
   btnParallelFor: TButton;
    Memo1: TMemo;
    procedure btnForLoopClick(Sender: TObject);
    procedure btnParallelForClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form18: TForm18;

const
  Max = 5000000;//计算1到Max间素数的个数.

function IsPrime(N: Integer): Boolean;//判断一个数是否为素数

implementation

{$R *.fmx}
//这是普通的实现方法,用For循环
procedure TForm18.btnForLoopClick(Sender: TObject);
var
  I, Tot: Integer;
  SW: TStopwatch;//秒表,计算耗用时间
begin
  // counts the prime numbers below a given value
  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('Sequential For loop. Time (in milliseconds): %d - Primes found: %d',
   [SW.ElapsedMilliseconds, Tot]));
end;

//这是用并行的实现方式
procedure TForm18.btnParallelForClick(Sender: TObject);
var
  Tot: Integer;
  SW: TStopwatch;
begin
  try
    // counts the prime numbers below a given value
    Tot := 0;
    SW := TStopwatch.Create;
   SW.Start;
    //这里用TParallel.For实现
   TParallel.For(2, 1, Max,
     procedure(I: Int64)
     begin
       if IsPrime(I) then
         TInterlocked.Increment(Tot);//累计Tot的时候,做线程保护
     end);
   SW.Stop;
   Memo1.Lines.Add(Format('Parallel For loop. Time (in milliseconds): %d - Primes found: %d',
     [SW.ElapsedMilliseconds, Tot]));
  except
    on E: EAggregateException do
     ShowMessage(E.ToString);
  end;
end;

//判断一个数是否为素数的函数
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; { jump out of the for loop }
     end;
     Test := Test + 6;
    end;
  end;
end;

end.

来源:http://blog.sina.com.cn/s/blog_44fa172f0102w4tp.html