日期:2014-05-18  浏览次数:20735 次

.NET4.0 并行循环效率对比测试
做了个.NET4.0 并行循环效率对比测试,发现并行效率居然比普通循环还要低。
请大家看看,是我代码问题还是微软忽悠人?
C# code
class Program
    {
        static void Main(string[] args)
        {
            Stopwatch timer1 = new Stopwatch();
            Stopwatch timer2 = new Stopwatch();
            timer1.Start();
            int max=10000000;
            ConcurrentQueue<int> intQueue = new ConcurrentQueue<int>();
            ConcurrentQueue<int> intQueueParallel = new ConcurrentQueue<int>();
            for (int i = 0; i < max; i++)
            {
                intQueue.Enqueue(i);
            }    
            //List< int> intList=intQueue.ToList<int>();
            timer1.Stop();
            Console.WriteLine("普通循环共耗时:" + timer1.Elapsed.TotalSeconds + "秒");
 
            timer2.Start();
            Parallel.For(0, max, (i) => intQueueParallel.Enqueue(i));
            //List<int> intListParallel = intQueueParallel.ToList<int>();
            timer2.Stop();
            Console.WriteLine("并行共耗时:"+timer2.Elapsed.TotalSeconds+"秒");
            Console.ReadKey();
        }
    }


normal:1.22s
parallel:1.61s

------解决方案--------------------
探讨

我重新做了个测试:
C# code
class Program
{
static void Main(string[] args)
{
Stopwatch timer1 = new Stopwatch();
Stopwatch timer2 = new Stopwatch();
……

------解决方案--------------------
好歹看下MSDN再开始干啊

当 For() 循环的循环体很小时,它的执行速度可能比等效的顺序循环更慢。 对数据进行分区所涉及的开销以及调用每个循环迭代上的委托的开销导致了性能降低。 为了解决类似情况,Partitioner 类提供 Create 方法,该方法使您可以为委托体提供顺序循环,以便每个分区只调用一次委托,而不是每个迭代调用一次委托。 有关更多信息,请参见 PLINQ 和 TPL 的自定义分区程序。 

http://msdn.microsoft.com/zh-cn/library/dd560853.aspx