Delphi XE7并行编程: 并行For循环

从Delphi XE7开始,引入了全新的并行编程库用于简化并行编程,它位于System.Threading单元中。

下面是一个判断素数的简单例子:

function IsPrime (N: Integer): Boolean;

var

Test: Integer;

begin

IsPrime := True;

for Test := 2 to N - 1 do

if (N mod Test) = 0 then

begin

IsPrime := False;

break; {jump out of the for loop}

end;

end;

传统方式是循环按顺序逐个检测1到X间的数字,然后把总数存放到一个变量里(此处的Tot是一个Integer)

const

Max = 50000; // 50K

for I := 1 to Max do

begin

if IsPrime (I) then

Inc (Tot);

end;

使用新的并行库,此处可以把for语句替换为类函数TParallel.For,然后把要执行的代码放到匿名过程里,作为参数传递给它。

另外,因为现在是多线程运行,为了避免出现问题,还应当把Inc替换为TInterlocked.Increment

TParallel.For(1, Max, procedure (I: Integer)

begin

if IsPrime (I) then

TInterlocked.Increment (Tot);

end);

为了检查效率上的区别,我们可以使用System.Diagnostics单元的TStopWatch来测试各版本的运行时间。

在我的双核VM上,标准for循环用时415毫秒,并行for循环则用时192毫秒。

同样的测试在我的Mac上,标准for循环用时382毫秒,并行for循环用时90毫秒。

转载:https://tieba.baidu.com/p/3314069553?red_tag=1510433701