浅谈.Net并行计算之数据并行(2)


Parallel.ForEach<int, long>(lista, () => 0, (j, loop, subsum) =>
       {
           if (subsum > 20000)
           {
               loop.Break();
           }

           subsum += lista[j];
           return subsum;

       }, (x) => Interlocked.Add(ref sum, x));

• Parallel.For 和for 性能测试比较 我们这里产生1千万个随机数为例子做个一个性能比较,在笔者的笔记本上结果如下 (可能在你的电脑上得到结果不一定相同)

浅谈.Net并行计算之数据并行

附上相关的代码给大家参考

复制代码 代码如下:


int listLength = 10000000;
            List<int> listTask = new List<int>();
            List<int> list = new List<int>();
            Stopwatch watch1 = Stopwatch.StartNew();

Parallel.For(0, listLength, i => {
                Random r = new Random(100);
                listTask.Add(r.Next());

            });
            Console.WriteLine("并行耗时:" + watch1.ElapsedMilliseconds );
           


            Stopwatch watch2 = Stopwatch.StartNew();

for (int i = 0; i < listLength; i++)
            {
                Random r = new Random(100);
                list.Add(r.Next());
            }


            Console.WriteLine("非并行耗时:" + watch2.ElapsedMilliseconds );

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjgygy.html