加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

【转】Delphi XE7并行编程: TParallel.For循环

(2016-07-08 13:31:47)
分类: Delphi10.1
从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毫秒。

原文地址
,向作者感谢.

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有