天天看点

Parallel.For

Parallel.For方法并行的执行for循环,它又多个重载。最常用的就是

For(Int32, Int32, Action<Int32>)

本人测试了一个求和方法,分别用传统的for语句和Parallel.For,结果发现,for语句不仅计算正确,而且速度比并行更快。而Parallel.For计算机结果还是不正确的。

这是由于Parallel.For在计算时要调用委托,也会消耗相当量的开销,所以仅仅在方法开销很大的时候,用并行才能体现出效率。

其次,之前的文章介绍过,给变量赋值对于大多数cpu来说都不是原子操作,而是需要分成3步的。C#的Interlocked类。所以导致sum求和并不能始终会有正确值。解决方法是加锁,用lock或者Interlocked

即便这样,经过测试:parallel.For的最后一个参数,Action委托直接写拉姆达表达式效率最低。写匿名委托效率高一些。不知道这是为何。

当在for循环里运行while循环来模拟复杂计算时,并行的For方法明显比单纯的for循环效率就高了。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

using System.Threading.Tasks;

using System.Diagnostics;

namespace ConsoleApplication1

{

    class Program

    {

        static long sum = 0;

        static void Main(string[] args)

        {

            //sequential

            Console.WriteLine("sequential");

            object alock = new object();

            var sw = Stopwatch.StartNew();

            for (int i = 0; i < 100000; i++)

            {

                sum += i;

            }

            Console.WriteLine(sw.Elapsed.ToString());

            Console.WriteLine(sum.ToString());

            Console.WriteLine("parallel");

            sum = 0;

            sw = Stopwatch.StartNew();

            Parallel.For(0, 100000, (i) =>

            });

            Parallel.For(0, 100000, delegate(int i)

            Parallel.For(0, 100000, a);

            for (int i = 0; i < 20; i++)

                int j = 0;

                while (j < 100000)

                {

                    j++;

                }

            Parallel.For(0, 20, delegate(int i)

        }

        static Action<int> a = Sum;

        static void Sum(int i)

            sum += i;

    }

}

继续阅读